I know this is a new guy question, but I cant find anything. I think the issue might have to do with variable type issue?
I'm trying to look at a files name and see if pattern1 is contained in the file name. If so then replace the pattern text with "TEST".
Right now it doesn't error out, but it skips the IF
, I do have files with the pattern in the directory.
Can't insert actually code, so here is a sample
$pattern1 = "January"
$pattern2 = "December 31"
$path = "C:\Users\...\METRICS-TEST\Metrics 2014\January 2014 Client Metrics"
$search_results = Get-ChildItem -Path $path | Where-Object { ((! $_.PSIsContainer))}
foreach ($file in $search_results) {
if($file.Name -contains $pattern1){
$new_name = $file.Name -replace $pattern1, "TEST1"
Rename-Item -Path $file.FullName -NewName $new_name
}else{
$new_name = $file.Name -replace $pattern2, "TEST2"
Rename-Item -Path $file.FullName -NewName $new_name
}
}
-contains
work on collections, not strings.
For strings, you'd want either -match
(for RegEx matching) or -like
for simple wildcard matching:
$file.name -match $pattern1
$file.name -like "*$pattern1*"
-contains
would be appropriate if you had an array of strings and wanted to know if it contained one or more copies of a specific string:
$Strings = "abc","def","ghi","jkl"
# This evaluates to true
$Strings -contains "abc"
# This evaluates to false
$Strings -contains "ab"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With