Powershell variables to string
Posted
by Mike Koerner
on Geeks with Blogs
See other posts from Geeks with Blogs
or by Mike Koerner
Published on Fri, 28 May 2010 18:35:40 GMT
Indexed on
2010/05/28
18:53 UTC
Read the original article
Hit count: 357
I'm new to powershell. I'm trying to write an error handler to wrap around my script. Part of the error handler is dumping out some variable settings. I spent a while trying to do this and couldn't google a complete solution so I thought I'd post something.
I want to display the $myinvocation variable. In powershell you can do this
PS C:\> $myInvocation
for my purpose I want to create a stringbuilder object and append the $myinvocation info. I tried this
$sbOut = new-object System.Text.Stringbuilder
$sbOut.appendLine($myinvocation)
$sbOut.ToString()
This produces
Capacity MaxCapacity Length
-------- ----------- ------
86 2147483647 45
System.Management.Automation.InvocationInfo
This is not what I wanted so I tried
$sbOut.appendLine(($myinvocation|format-list *))
This produced
Capacity MaxCapacity Length
-------- ----------- ------
606 2147483647 305
Microsoft.PowerShell.Commands.Internal.Format.FormatStartData Microsoft.PowerShell.Commands.Internal.Format.GroupStartData Micros
oft.PowerShell.Commands.Internal.Format.FormatEntryData Microsoft.PowerShell.Commands.Internal.Format.GroupEndData Microsoft.Powe
rShell.Commands.Internal.Format.FormatEndData
Finally I figured out how to produce what I wanted:
$sbOut = new-object System.Text.Stringbuilder
[void]$sbOut.appendLine(($myinvocation|out-string))
$sbOut.ToString()
MyCommand : $sbOut = new-object System.Text.Stringbuilder
[void]$sbOut.appendLine(($myinvocation|out-string))
$sbOut.ToString()
BoundParameters : {}
UnboundArguments : {}
ScriptLineNumber : 0
OffsetInLine : 0
HistoryId : 13
ScriptName :
Line :
PositionMessage :
InvocationName :
PipelineLength : 2
PipelinePosition : 1
ExpectingInput : False
CommandOrigin : Runspace
Note the [void] in front of the stringbuilder variable doesn't show the Capacity,MaxCapacity of the stringbuilder object. The pipe to out-string makes the output a string.
It's not pretty but it works.
© Geeks with Blogs or respective owner