The file name contains specific text
I know this is a new guy's question, but I can't seem to find anything. I think the problem might be related to the variable type issue?
I am trying to look at the filename and see if the pattern is contained in the filename. If so, replace the template text with "TEST".
This is not a bug at the moment, but it misses IF
, I have template files in the directory.
It is not possible to insert the actual code, so here is an example
$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
}
}
source to share
The whole problem is that you are using -Contains where you should be using -Match. Try this, however, it expands easily if you have additional conditions to add:
$pattern1 = "January"
$pattern2 = "December 31"
$path = "C:\Users\...\METRICS-TEST\Metrics 2014\January 2014 Client Metrics"
Switch(Get-ChildItem -Path $path){
{$_.Name -match $pattern1}{$new_name = $_.Name -replace $pattern1, "TEST1"
Rename-Item -Path $_.FullName -NewName $new_name}
{$_.Name -match $pattern2}{$new_name = $_.Name -replace $pattern2, "TEST2"
Rename-Item -Path $_.FullName -NewName $new_name}
}
source to share
-contains
work with collections, not strings.
For strings, you need either -match
(for RegEx matching) or -like
for simple wildcard matching:
$file.name -match $pattern1
$file.name -like "*$pattern1*"
-contains
it would be pertinent if you had an array of strings and wanted to know if it contains 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"
source to share
I realize I have an accepted answer, but I thought another elegant way to deal with this would be to display Old-To-New in a hashtable, matching against the keys of that hashtable (regex escaped and connected to pipes to form a regular expressions pattern match) and then renamed to ForEach against matches, not a switch. I guess at the moment everything is academic.
$path = "C:\Users\...\METRICS-TEST\Metrics 2014\January 2014 Client Metrics"
$RenameMap = @{
"January" = "Test1"
"December 31" = "Test2"
}
$Pattern = "($(($RenameMap.keys|ForEach{[regex]::Escape($_)}) -join "|"))"
Get-ChildItem $Path | Where{$_.Name -match $Pattern} | ForEach {Rename-Item $_.FullName -NewName ($_.Name -Replace $Matches[1],$RenameMap[$Matches[1]])}
source to share