首页 > 解决方案 > Powershell设置内容替换字符串

问题描述

所以,我需要保存一个在文件上被替换的字符串。

我做错了什么,但我无法弄清楚,什么!

我的代码:

    Get-ChildItem -Path C:\Users\user\Documents -Recurse -Include "*.txt" -File |  Select-String  -Pattern \b192\.168\.10\.2\b , \b192\.168\.10\.11\b -AllMatches -List |  Foreach-Object { $_ -replace '\b192\.168\.10\.2\b', "DEV" -and $_ -replace '\b192\.168\.10\.11\b', "QUAL" | Set-Content $_}

并给我以下错误:

   Set-Content : Could not open the alternate data stream '1:192.168.10.11' of the file 'C:\Users\user\Documents\result.txt'.
   At line:1 char:323
   + ... place '\b192\.168\.10\.11\b', "QUAL" | Set-Content $_}
   +                                                         
   + CategoryInfo : ObjectNotFound: (C:\Users\paulo....ents\result.txt:String) [Set-Content], FileNotFoundException
   + FullyQualifiedErrorId :  GetContentWriterFileNotFoundError,Microsoft.PowerShell.Commands.SetContentCommand

   Set-Content : Could not open the alternate data stream '1:192.168.10.11' of the file 
  'C:\Users\user\Documents\test.txt'
   At line:1 char:323 ... place '\b192\.168\.10\.11\b', "QUAL" | Set-Content $_}                                                             
   CategoryInfo : ObjectNotFound: (C:\Users\user\test.txt:String) [Set-Content], FileNotFoundException
   FullyQualifiedErrorId : GetContentWriterFileNotFoundError,Microsoft.PowerShell.Commands.SetContentCommand

谢谢你的帮助!

标签: powershell

解决方案


-and运算符用于内部if测试,例如if(this -and that).
您应该将双重替换操作从

$_ -replace '\b192\.168\.10\.2\b', "DEV" -and $_ -replace '\b192\.168\.10\.11\b', "QUAL"

进入

$_ -replace '\b192\.168\.10\.2\b', "DEV" -replace '\b192\.168\.10\.11\b', "QUAL"

另外,如果我正确理解了这个问题,您希望在文件中找到所有字符串替换,并且要获取所有内容,您需要-List从 Select-String 中删除开关。

接下来,正如 Mathias 在他的回答中解释的那样,您需要使用Path当前匹配中的属性来获取文件 FullName.
但是,如果您直接将其通过管道传递给 Set-Content,您将收到异常,因为该文件正在使用中,您无法写入同一个文件。

下面在同一路径中创建一个新文件,_replacements并附加到文件名

# use '-Include' instead of '-Filter' if you need more file extensions to filter on
Get-ChildItem -Path 'C:\Users\user\Documents' -Recurse -Filter "*.txt" -File |  
Select-String  -Pattern '\b192\.168\.10\.2\b', '\b192\.168\.10\.11\b' -AllMatches |  
Foreach-Object { 
    $file = '{0}_replacements{1}' -f [System.IO.Path]::GetFileNameWithoutExtension($_.Path),
                                     [System.IO.Path]::GetExtension($_.Path)
    $target = Join-Path -Path ([System.IO.Path]::GetDirectoryName($_.Path)) -ChildPath $file
    $_ -replace '\b192\.168\.10\.2\b', "DEV" -replace '\b192\.168\.10\.11\b', "QUAL"  | 
    Add-Content -Path $target 
}

这会生成一个名为“C:\Users\user\Documents\test_replacements.txt”的文件

C:\Users\user\Documents\test.txt:4:DEV
C:\Users\user\Documents\test.txt:7:QUAL

原始文件 'C:\Users\user\Documents\test.txt' 不会被更改。


推荐阅读