【问题标题】:Powershell - Find Files by Searching for String and Find/Replace TextPowershell - 通过搜索字符串和查找/替换文本来查找文件
【发布时间】:2018-05-11 13:48:03
【问题描述】:

我正在学习powershell并尝试编写一个脚本,该脚本可以通过字符串在目录中查找文件,然后对找到的文件进行查找和替换。我想将文件列表存储为变量,然后遍历文件并替换特定的字符串。这是我的脚本和错误,如果您有任何想法,将不胜感激。谢谢!

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

错误

Get-Content:无法将参数绑定到参数“路径”,因为它是 空值。在 C:\scripts\script.ps1:5 char:18 +(获取内容 $Files.PSPath)|Foreach 对象 { + ~~~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand

【问题讨论】:

    标签: powershell replace


    【解决方案1】:
    $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
    }
    

    在 foreach 中,您定义了名为 $File 的变量,但在您的 foreach 语句中,您是 $Files 而不是 $File

    在第 1 行,最后使用Select-Object Filename,$GetFiles 的对象只有一个属性 Filename。所以 PSPath 属性不存在。这就是为什么你得到空错误。 BTW Select-String 命令的输出没有 PSPath 属性。

    【讨论】:

    • 太棒了,感谢文森特 K 的解释!
    猜你喜欢
    • 1970-01-01
    • 2011-05-25
    • 2017-06-15
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 2021-10-18
    • 2011-03-14
    • 1970-01-01
    相关资源
    最近更新 更多