Advertisement
guyrleech

Parse cmdkey.exe output into PowerShell

Nov 9th, 2022 (edited)
1,218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ## PowerShell to turn cmdkey.exe output into objects
  2. ## Could be used for parsing other text - uses blank line as terminator for an object but check for first field name if no blank line
  3.  
  4. ## 1 liner for copy/paste into PS command line
  5.  
  6. $o = $null ; cmdkey /list | Select -skip 2 | % { $f = $_.Trim() ; if( $f -match '^\s*$' ) { if( $o ) { $o ; $o = $null } } else { if( -Not $o ) { $o = New-Object pscustomobject }; if( $f.IndexOf( ':' ) -gt 0 ) { $s = ($f -split ':' , 2).Trim() ; Add-Member -InputObject $o -MemberType NoteProperty -Name $s[0] -Value $s[-1] } else { Add-Member -InputObject $o -MemberType NoteProperty -Name 'Persistence' -Value $f } } }
  7.  
  8. ## For use in scripts with vaguely meaningful variable names and formatted better
  9.  
  10. $object = $null
  11. cmdkey /list | Select-Object -skip 2 | ForEach-Object {
  12.     $field = $_.Trim()
  13.     if( $field -match '^\s*$' ) {
  14.         if( $object ) {
  15.             $object
  16.             $object = $null }
  17.     } else {
  18.         if( -Not $object ) {
  19.             $object = New-Object pscustomobject }
  20.             ## one field is not : delimited so have to treat as special
  21.             if( $field.IndexOf( ':' ) -gt 0 ) {
  22.                 $splits = ($field -split ':' , 2).Trim()
  23.                 Add-Member -InputObject $object -MemberType NoteProperty -Name $splits[0] -Value $splits[-1]
  24.         } else {
  25.             Add-Member -InputObject $object -MemberType NoteProperty -Name 'Persistence' -Value $field
  26.         }
  27.     }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement