user1595214
user1595214

Reputation: 551

Replace multiple strings in a file using powershell

I am using following coe to replace the string

$folders=Get-ChildItem -Path "C:\temp\Database Scripts"
foreach($folder in $folders)
{
    Write-Host $folder
    $spath=[string]::Concat("C:\temp\Database Scripts\", $folder)
    $subfolders=Get-ChildItem $spath 
    foreach($subfolder in $subfolders )
    {
        if($subfolder -match "Running Scripts")
        {
            $subfolerpath=[string]::Concat($spath,"\",$subfolder,"\*")  
            $files =get-childitem -Path $subfolerpath -include "AVEVAScripts*"
            if($files -ne $null)
            {
                foreach( $file in $files)
                {
                Write-Host $file;
                (Get-Content $file) | ForEach-Object {$_ -replace "DATABASE_USER","fhghjgj" `
                -replace "DATABASE_PASSWORD", "DFGHFHJGJH"  } |Set-Content $file 
                }
            }
        }       
    }
}

But ending up with following error.

Set-Content : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline input.

Please help :)

Upvotes: 1

Views: 8642

Answers (1)

Frode F.
Frode F.

Reputation: 54851

Remove the $x in the end of Set-Content. $x is never declared.

Also, you could simplify it a lot. Ex:

Get-ChildItem -Filter "Running Scripts" -Path "C:\temp\Database Scripts" -Recurse | ForEach-Object {
    Get-ChildItem -Path $_.FullName -Filter "AVEVAScripts*" -Recurse | ForEach-Object {
        (Get-Content $_.FullName) | ForEach-Object {
            $_ -replace "DATABASE_USER","fhghjgj" -replace "DATABASE_PASSWORD", "DFGHFHJGJH"
        } | Set-Content $_.FullName
    }
}

Or find all files that includes "AVEVAScripts" in it's name, then check if their full path includes "Running Scripts"

Get-ChildItem -Filter "AVEVAScripts*" -Path "C:\temp\Database Scripts" -Recurse | 
Where-Object { $_.FullName -like "*Running Scripts*" } | 
ForEach-Object {
    (Get-Content $_.FullName) | ForEach-Object {
        $_ -replace "DATABASE_USER","fhghjgj" -replace "DATABASE_PASSWORD", "DFGHFHJGJH"
    } | Set-Content $_.FullName
}

Upvotes: 4

Related Questions