Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File Name Contains Certain Text

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
    }
}
like image 929
Greg K Avatar asked Aug 22 '14 15:08

Greg K


1 Answers

-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"
like image 56
Mathias R. Jessen Avatar answered Sep 21 '22 23:09

Mathias R. Jessen