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.
$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.
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.