Replace multiple strings in a file using powershell

℡╲_俬逩灬. 提交于 2021-01-28 18:54:56

问题


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 :)


回答1:


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
}


来源:https://stackoverflow.com/questions/16646293/replace-multiple-strings-in-a-file-using-powershell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!