Dear PS members,
I have the following question. I have a file, I want to convert into a pscustomobject.
The file follows this format. Each section starts with exec: command name_ and it ends with “Done”
Something like:
exec: show ns version
NetScaler NS13.0: Build 47.24.nc, Date: Jan 20 2020, 06:11:41 (64-bit)
Done
exec: show ns hostName
Hostname: hostname1-adc-01
Done
exec: show ns ip -type NSIP
Ipaddress Traffic Domain Type Mode Arp Icmp Vserver State
--------- -------------- ---- ---- — ---- ------- ------
1) 10.0.0.4 0 NetScaler IP Active Enabled Enabled NA Enabled
Done
exec: show ns ip -type SNIP
Ipaddress Traffic Domain Type Mode Arp Icmp Vserver State
--------- -------------- ---- ---- — ---- ------- ------
1) 10.0.0.3 0 SNIP Active Enabled Enabled NA Enabled
Done
I was hoping to create a custom object where it has a key for each command and the value is the output of the command.
Something like $Object1.‘exec: show ns ip-type snip’ will display the output till the done and the same for the rest of the commands.
I have been playing around, and I manage to do it just for one command, but I am facing difficulties when trying to put all the commands into an object in one run.
Thanks in advance for your help!
Cheers,
#region Input
$myString = @'
exec: show ns version
NetScaler NS13.0: Build 47.24.nc, Date: Jan 20 2020, 06:11:41 (64-bit)
Done
exec: show ns hostName
Hostname: hostname1-adc-01
Done
exec: show ns ip -type NSIP
Ipaddress Traffic Domain Type Mode Arp Icmp Vserver State
——— ————– —- —- — —- ——- ——
1) 10.0.0.4 0 NetScaler IP Active Enabled Enabled NA Enabled
Done
exec: show ns ip -type SNIP
Ipaddress Traffic Domain Type Mode Arp Icmp Vserver State
——— ————– —- —- — —- ——- ——
1) 10.0.0.3 0 SNIP Active Enabled Enabled NA Enabled
Done
'@
#endregion
#region Process
#write the string to a file and read it as array
$Temp = New-TemporaryFile
$myString | Out-File $Temp
$myArray = Get-Content $Temp
$myObjStartMarker = 'exec:'
$myObjEndMarker = 'Done'
$myOutput= foreach ($Line in $myArray) {
if ($Line -match $myObjStartMarker) { # Start New object
$ExecCommand = $Line.Replace('exec: ','')
} elseif ($Line -eq $myObjEndMarker) { # End Object
New-Object -TypeName psobject -Property ([Ordered]@{
Command = $ExecCommand
Output = $CommandBody -join ''
})
$CommandBody = @()
} else { # not start or end ==> body
$CommandBody += $Line
}
}
#endregion
$myOutput
Thanks Sam, it worked like a charm. I was focusing in use a while statement and I was not getting my way around it. Thanks +++