1

I'm trying to prepend a PatientOrderNumber to the name of files in a directory if the file name includes a unique ID from my CSV file. I've tried the -like and -contains parameters and have not been successful.

here is my code:

$csvPath = "C:\Users\dougadmin28\Desktop\Test\1bs4e.csv"
## Variable to hold path of Files that need to be renamed ##
$filePath = "C:\Users\dougadmin28\Desktop\Node Modify File Name App\pdfs" 

$csv = Import-Csv $csvPath #| Select-Object -Property PatientOrderNumber, FileID, DocumentID, LastName, FirstName|Export-Csv 'C:\Users\dougadmin28\Desktop\Node Modify File Name App\documents.csv'

$files = Get-ChildItem $filePath 


    foreach ($item in $csv){  



            foreach($file in $files)  {     
               if($file.FullName -contains '*$item.DocumentID*') {

                Rename-Item $file.FullName -NewName "$($item.PatientOrderNumber+"_"+($item.FileID)+'_'+($item.DocumentID)+'_'+($item.LastName)+'_'+($item.FirstName)+($file.extension))" 

            }#End forEach

        }#End if

    } #End forEach```

1 Answers1

1

tl;dr

Instead of:

$file.FullName -contains '*$item.DocumentID*' # WRONG

use:

$file.FullName -like "*$($item.DocumentID)*"

Note the use of " instead of ' and the $(...) around the property-access expression.


As for what you tried:

$file.FullName -contains '*$item.DocumentID*'

  • -contains tests array membership of the RHS in the array-valued LHS, it doesn't perform substring matching.

    • See this answer for the difference between PowerShell's -contains operator and the String.Contains() .NET method.
  • '...' strings are taken literally (verbatim), so no expansion (interpolation) is performed; "..." (expandable strings) must be used for string interpolation.

  • Inside an expandable string, only simple variable references (e.g., $item) can be embedded as-is; anything more complex, such as an expression that involves property access (e.g. $item.DocumentID), requires enclosing in $(...), the subexpression operator.

    • See this answer for an overview of string expansion (interpolation) in PowerShell.
mklement0
  • 382,024
  • 64
  • 607
  • 775