使用powershell替换文件中的多个字符串

时间:2013-05-20 09:20:20

标签: powershell

我使用以下coe来替换字符串

$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 
                }
            }
        }       
    }
}

但最终会出现以下错误。

Set-Content:输入对象不能绑定到命令的任何参数,因为该命令不接受管道输入或输入及其属性与管道输入的任何参数都不匹配。

请帮助:)

1 个答案:

答案 0 :(得分:3)

删除$x末尾的Set-Content。永远不会宣布$x

另外,你可以简化它。例如:

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
    }
}

或者查找其名称中包含“AVEVAScripts”的所有文件,然后检查其完整路径是否包含“正在运行的脚本”

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
}