Search code examples
powershelltrimcharacter-trimming

Trim Powershell OutPut


Requirement is to trim the Output. Retain only the output quoted within double quotes from Name and remove/avoid the earlier lines/characters

From:

$R.Output = \\GBVServer1\root\cimv2:Win32_Group.Domain="Contoso",Name="Domain Users"

$R.Output = \\GBVServer1\root\cimv2:Win32_SystemAccount.Domain="GBVServer1",Name="INTERACTIVE"

To:

$R.Output = Domain Users

$R.Output = INTERACTIVE

Could somebody assist with the powershell switch to be used?


Solution

  • You can do this with regex to capture only the Name part between the quotes for these strings:

    $regex = [regex]'(?i)Name="([^,]+)"'
    
    $string = '\\GBVServer1\root\cimv2:Win32_Group.Domain="Contoso",Name="Domain Users"'
    $R.Output = $regex.Match($string).Groups[1].Value  # --> Domain Users
    
    $string = '\\GBVServer1\root\cimv2:Win32_SystemAccount.Domain="GBVServer1",Name="INTERACTIVE"'
    $R.Output = $regex.Match($string).Groups[1].Value  # --> INTERACTIVE
    

    Regex details:

    Name="      Match the characters “Name="” literally
    (           Match the regular expression below and capture its match into backreference number 1
       [^,]     Match any character that is NOT a “,”
          +     Between one and unlimited times, as many times as possible, giving back as needed (greedy)
    )
    "           Match the character “"” literally
    

    The (?i) makes the match case-insensitive