Search code examples
powershellsubstringslash

Finding substring in string with forward slash in Powershell scripts


I am trying to find sub-string in string using powershell script. Actually, I am reading a file line by line which contains thousands of paths. I am filtering each path coming from file. Path filters are finding sub-string in path. But Contains function returns false when sub-string is Sroot or TRoot.

Following is my sample code.

foreach($line in Get-Content $filePath)
{
    # Line can contain
    # $line = $/Patil/TEMP/PRoot/Digvijay/Patil/1.png 
    # $line = $/Patil/TEMP/SRoot/Digvijay/Patil/2.png
    # $line = $/Patil/TEMP/TRoot/Digvijay/Patil/3.png
    if($line)
    {        
        if($line.Contains('RRoot')) # This condition works properly
        {                       
            # Process Rroot here
        }                       
        if($line.Contains('SRoot')) # This condition fails.
        {
            # Process SRoot here
        }
        if($line.Contains('TRoot')) # This condition fails.
        {
            # Process TRoot here
        }
    }
 }

Input file is like:

$/Patil/TEMP/PRoot/Digvijay/Patil/1.png
$/Patil/TEMP/SRoot/Digvijay/Patil/2.png
$/Patil/TEMP/TRoot/Digvijay/Patil/3.png
$/Patil/TEMP/WRoot/Digvijay/Patil/3.png

Solution

  • Instead of using multiple IFs

    • you could use a switch controlled by the letter in front of Root determined by
    • a RegEX storing the matched char in a capture group () recallable via $Matches[1]:

    $filePath = '.\files.txt'
    Get-Content $filePath | Where-Object {$_ -match '([PST])Root'} | ForEach-Object {
        $line = $_
        switch ($Matches[1]){
            'P' {'{0}={1}' -f $_,$line} # code in {} to execute on P
            'S' {'{0}={1}' -f $_,$line} # code in {} to execute on S
            'T' {'{0}={1}' -f $_,$line} # code in {} to execute on T
        }
    }
    

    Sample output:

    P=P:/TEMP/PRoot/Digvijay/Patil/1.png
    S=S:/TEMP/SRoot/Digvijay/Patil/2.png
    T=T:/TEMP/TRoot/Digvijay/Patil/3.png
    

    PS: the -match operator and the switch statement are by default case insensitive,
    to change that behaviour use -cmatch resp. switch with the -CaseSensitive parameter.