Powershell variables to string
- by Mike Koerner
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.