Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Powershell Array values contain no values from wildcard array

I have the following code

@Wildcard_Array = @ ( '"' , '[' , ']' , '*' )
$SAMAccounts = Import-Excel -Path $PSScriptRoot\PulledData.xlsx | Where-Object -Property SAM_ACCOUNT_NAME -notcontains @Wildcard_Array

What I’m trying to accomplish is that no values are returned that contain wildcard values.

If I use this I can filter dates which I want to I just don’t know how to filter out and values with wildcards/invalid options.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$SAMAccounts = Import-Excel -Path $PSScriptRoot\PulledData.xlsx | Where-Object -Property DT -eq (Get-Date -Hour 0 -Minute 0 -Second 0 -Format G | Select-Object -ExpandProperty SAM_ACCOUNT_NAME

Example:

SAM_ACCOUNT_NAME     DT
!@$#*                1/11/2024
User1                1/11/2024

I’ve tried contains, notcontains, cnotconains, notlike, and inotlike but honestly I’m not sure what i’m doing wrong. Thank you so much for your time.

>Solution :

You could use .IndexOfAny in this case:

$Wildcard_Array = [char[]] ('"', '[', ']' , '*')

@'
SAM_ACCOUNT_NAME,DT
!@$#*,1/11/2024
User1,1/11/2024
'@ | ConvertFrom-Csv |
    Where-Object { $_.SAM_ACCOUNT_NAME.IndexOfAny($Wildcard_Array) -eq -1 }

Another option could be to convert your array into a regex pattern and use -notmatch:

$Wildcard_Array = '"', '[', ']' , '*' | ForEach-Object { [regex]::Escape($_) }
$filter = '(?:{0})' -f ($Wildcard_Array -join '|')

@'
SAM_ACCOUNT_NAME,DT
!@$#*,1/11/2024
User1,1/11/2024
'@ | ConvertFrom-Csv |
    Where-Object SAM_ACCOUNT_NAME -NotMatch $filter

-contains looks for an exact match in a collection, so it isn’t an option:

'foo', 'bar' -contains 'bar' # True
'foo', 'bar' -contains 'b'   # False

And -like would require to first escape the wildcard characters (can use [WildcardPattern]::Escape similar to [regex]::Escape) and then use additional wildcards. I wouldn’t recommend this method in this case.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading