Welcome › Forums › General PowerShell Q&A › how to process file to ceate customobject
- This topic has 2 replies, 2 voices, and was last updated 1 week, 5 days ago by
Participant.
-
AuthorPosts
-
-
January 13, 2021 at 6:55 pm #285682
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
DoneI 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,
-
January 14, 2021 at 5:58 am #285739PowerShell1234567891011121314151617181920212223242526272829303132333435363738394041424344454647#region Input$myString = @'exec: show ns versionNetScaler NS13.0: Build 47.24.nc, Date: Jan 20 2020, 06:11:41 (64-bit)Doneexec: show ns hostNameHostname: hostname1-adc-01Doneexec: show ns ip -type NSIPIpaddress Traffic Domain Type Mode Arp Icmp Vserver State——— ————– —- —- — —- ——- ——1) 10.0.0.4 0 NetScaler IP Active Enabled Enabled NA EnabledDoneexec: show ns ip -type SNIPIpaddress Traffic Domain Type Mode Arp Icmp Vserver State——— ————– —- —- — —- ——- ——1) 10.0.0.3 0 SNIP Active Enabled Enabled NA EnabledDone'@#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 ObjectNew-Object -TypeName psobject -Property ([Ordered]@{Command = $ExecCommandOutput = $CommandBody -join ''})$CommandBody = @()} else { # not start or end ==> body$CommandBody += $Line}}#endregion$myOutput
-
January 14, 2021 at 6:10 am #285742
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 +++
-
-
-
AuthorPosts
- You must be logged in to reply to this topic.