【问题标题】:Replace multiple strings in a file using powershell使用powershell替换文件中的多个字符串
【发布时间】:2013-05-20 09:20:19
【问题描述】:

我正在使用以下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 : 输入对象不能绑定到命令的任何参数,因为命令不接受管道输入,或者输入及其属性不匹配任何接受管道输入的参数。

请帮忙:)

【问题讨论】:

  • 删除 $x 末尾的 Set-Content 。你还没有在任何地方声明它。
  • @Graimer 感谢 Graimer,这是错误留下的,它起作用了 :)
  • 将其添加为答案,并使用另一种使用管道解决它的方法(未经测试)。
  • 不要使用字符串连接来创建文件系统路径。请改用Join-Path。它不能解决您的问题,但可以让您的代码更简洁、更安全。
  • @alroc 非常感谢,我一定会使用它。

标签: powershell


【解决方案1】:

删除Set-Content 末尾的$x$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”的所有文件,然后检查其完整路径是否包含“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
}

【讨论】:

  • 非常感谢你让它变得如此简单,这正是我想要的。
猜你喜欢
  • 1970-01-01
  • 2015-11-07
  • 2011-03-25
  • 2023-03-28
  • 2021-03-20
  • 2017-06-23
  • 1970-01-01
  • 2014-09-29
  • 1970-01-01
相关资源
最近更新 更多