Home > Enterprise >  Matching string which might contain whitespace when using Where-Object
Matching string which might contain whitespace when using Where-Object

Time:04-02

I need a PowerShell script that will check whether specific user is a part of certain group or not and if the user is part of any of those groups.

But ,it does not correctly working. I am assuming there is an issue regarding $_ -match 'CN=IT Tool ((TST) Users|(PROD) Users)' Also there are whitespaces for below security groups.

Lastly ,I want to get an output via Export-CSV.

There are two groups :

IT Tool (TST) Users
IT Tool (PROD) Users

SCRIPT:

$csv = import-csv "c:\tmp\lists.csv"


foreach ($v in $csv) {
    $userinput = $v.userinput
Get-ADUser -Identity $userinput -Properties EmailAddress, MemberOf | ForEach-Object {
    $testgroups = $_.MemberOf | Where-Object { $_ -match 'CN=IT Tool ((TST) Users|(PROD) Users)' }  
    if ($testgroups) {
        # the user is a member of group IT_Test and/or IT_Prod, get the names of these groups for this user
        $groups = foreach ($grp in $testgroups) { (Get-ADGroup -Identity $grp).Name }
        $_ | Select-Object Name, SamAccountName, @{Name = 'MemberOf'; Expression = {$groups -join ', '}}
    }
    else {
        # the user is not a member of any IT_Group
        $_ | Select-Object Name, SamAccountName, @{Name = 'MemberOf'; Expression = {'Not a member of any Group'}}
    }
}

}

CodePudding user response:

You need to escape any literal ( or ) in the group name since these characters will otherwise be interpreted as grouping constructs:

$testgroups = $_.MemberOf | Where-Object { $_ -match 'CN=IT Tool (\(TST\) Users|\(PROD\) Users)' }

Since the TST/PROD part is the only thing that varies between the two possible group names, you can simplify the pattern further:

$testgroups = $_.MemberOf | Where-Object { $_ -match 'CN=IT Tool \((TST|PROD)\) Users)' }

To export the results to a CSV, simply collect the output from the loop to a variable, and then pipe the variable contents to Export-Csv:

$results = foreach($v in $csv) {
  # ...
}

$results |Export-Csv -Path path\to\output.csv -NoTypeInformation
  • Related