Reputation: 16724
I'm trying to filter a file extension equal to .config
and file name doesn't contains vshost in the name, so I run this script:
$files = dir
foreach($file in $files) {
if($file.Name -notcontains 'vshost' -and $file.Extension -eq '.config') {
Write-Host $file;
}
}
But the output still contains files with vshost
in the name:
foo.exe.config
foo.vshost.exe.config
foo2.vshost.exe.config
the expected output is:
foo.exe.config
What am I missing and how do I fix this?
Upvotes: 1
Views: 104
Reputation: 553
-contains/-notcontains
is used to check if a list contains an element. You can use the -like / -notlike
or the -match
operator.
In your sample you could use
$files = dir
foreach($file in $files) {
if($file.Name -notlike '*vshost*' -and $file.Extension -eq '.config') {
Write-Host $file;
}
}
A reference can be found here
Upvotes: 3
Reputation: 54891
-notcontains
is used to look for an item in an array, ex. $array -notcontains $singleitem
. You need to use -notlike
or -notmatch
(regex-patterns). Ex.
if($file.Name -notlike '*vshost*' -and $file.Extension -eq '.config') {
or
if($file.Name -notmatch 'vshost' -and $file.Extension -eq '.config') {
Upvotes: 4