Home > Blockchain >  How to find if Powershell Array Contain part of another Array
How to find if Powershell Array Contain part of another Array

Time:09-28

I have 2 Arrays

$Array1 = Get-Disabledusers SIDS
$Array2 =  %Unnecessarytext(SIDS).VHDX

I need to compare Array1 and Array2 and output only the things in Array2 that contain Array1. Thing is, when I compare both objects, it returns not equal because they don't match exactly.

How do I get it to output the items in Array2 that contain the matching Disabled Users SIDS? Should I run a foreach loop and compare a part of the Array?

I found this: How to find if Powershell Array Contains Object of Another Array

However this doesn't help as it will return not equal.

Clarified Question:

There is a folder in which there are VHDXs. The VHDXs are named based on a user's SID. However, there is a bunch if unnecessary text before and after the SIDs.

In Array1, I run:

Get-ADUser -Filter {Enabled -eq $false} | FT SID

In order to retrieve a list of disabled users and filter out their SIDs.

In Array2, I list the names of the files in the VHDX folder which look like this: text SID text. I want to compare both and return which files in the VHDX folders contain the SIDS of the disabled users.

CodePudding user response:

You can do it this way, first get the list of SID values from all disabled users and store them in a variable, then since the files or folders (unclear on this) are not exact SIDs, you will need to first check if they contain a valid SID, this can be accomplished using a regular expression and the -match operator and if they do, then we can use the automatic variable $Matches to check if the SID is -in the array of SIDs of Disabled Users, if yes, we can output that file or folder and store it in $result:

$re = 'S-1-[0-59]-\d{2}-\d{8,10}-\d{8,10}-\d{8,10}-[1-9]\d{2,3}'
$sids = (Get-ADUser -Filter "Enabled -eq '$false'").SID.Value
$result = foreach($item in Get-ChildItem -Path path\to\something) {
    if($item.Name -match $re) {
        if($Matches[0] -in $sids) {
            $item
        }
    }
}

$result # => has all the files or folders existing in `$sids`

The regex used was taken from this answer and only required to change the last \d{3} for \d{2,3} to match any valid SID.

  • Related