0
votes

I'm learning powershell and trying to write a script that can find files in a directory by a string, and then do a find and replace on the files that are found. I want to store the file list as a variable and then loop through the files and replace specific strings. Here's my script and error, if you have any ideas it would be much appreciated. Thanks!

$GetFiles = Select-String -path "C:\temp\*.xml" -pattern "<cmn:BusinessName>ABC INC</cmn:BusinessName>"|Select-Object filename

foreach ($file in $GetFiles)
{
    (Get-Content $Files.PSPath) |Foreach-Object { 
    $_ -replace "<cmn:FileNumber>0001234</cmn:FileReceiverNumber>", "<cmn:FileReceiverNumber>12345678</cmn:FileReceiverNumber>" `
    -replace "<cmn:DropIndicator>DROP</cmn:Indicator>", "<cmn:DropIndicator>DONTDROP</cmn:DropIndicator>"
    } |Set-Content $Files.PSPath
}

ERROR

Get-Content : Cannot bind argument to parameter 'Path' because it is null. At C:\scripts\script.ps1:5 char:18 + (Get-Content $Files.PSPath) |Foreach-Object { + ~~~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand

1

1 Answers

0
votes
$GetFiles = Select-String -Path "C:\temp\*.xml" -Pattern "<cmn:BusinessName>ABC INC</cmn:BusinessName>"

foreach ($File in $GetFiles)
{
    $NewContent = Get-Content $File.Path | Foreach-Object { 
        $_ -replace "<cmn:FileNumber>0001234</cmn:FileReceiverNumber>", "<cmn:FileReceiverNumber>12345678</cmn:FileReceiverNumber>" `
           -replace "<cmn:DropIndicator>DROP</cmn:Indicator>", "<cmn:DropIndicator>DONTDROP</cmn:DropIndicator>"
    } 
    $NewContent | Set-Content $File.Path
}

In foreach, you have defined variable named $File but in inside your foreach statement, you are $Files instead of $File

In Line 1, by using Select-Object Filename in the end, $GetFiles has object with only one property Filename. So PSPath property doesn't exist. that is why you getting the null error. BTW the output of Select-String command doesn't have PSPath property.