powershell - 使用 PowerShell 替换文件中的字符串

标签 powershell

我正在尝试替换另一个 PowerShell 文件中的几个字符串。

$Source_IP = Read-Host 'Enter source IP'
$Target_IP = Read-Host 'Enter target IP'

通过在另一个 PowerShell 脚本中使用以下行,文件显示为已修改,但更改不会生效。
(Get-Content "C:\Solutions.ps1") -replace "$Target_IP = Read-Host 'Enter target IP'", "$Target_IP = '192.168.0.221'" | Set-Content "C:\Solutions.ps1"

是否有更改不生效的原因?

我相信这是在 Windows Server 2008 和 PowerShell 版本 2 上以管理员身份运行的。

最佳答案

PetSerAl points out -replace比较运算符支持正则表达式。虽然您可以在您的模式中使用某种程度的表达式,但您会增加不必要的复杂性,尤其是因为您无论如何都只是使用简单的匹配。

更简单的解决方案是使用字符串方法 .Replace() .

$filePath = "C:\Solutions.ps1"
(Get-Content $filePath).Replace($Source_IP,$Target_IP) | Set-Content $filePath

请注意 .Replace()区分大小写。如果您只是替换 IP 地址,这是一个有争议的问题。我不确定您为什么会遇到第二个文件的问题。

关于powershell - 使用 PowerShell 替换文件中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35062320/

相关文章:

powershell - 获取最接近给定日期的文件

Powershell 异常 : Not enough quota is available to process this command

powershell - 将部分 IP 地址字符串转换为 IP 地址对象

powershell - 使用 Powershell 获取 Azure WebApp 的 PublishProfile

internet-explorer - PowerShell Internet Explorer Com 对象选择类下拉菜单项

xml - 如何使用 ConvertTo-Xml 和 Select-Xml 加载或读取 XML 文件?

entity-framework - Visual Studio 无法加载 Entity Framework PowerShell 脚本,因为其操作被软件限制策略阻止

powershell - 使用输出覆盖 Azure Function Table Store 行

powershell - 在 PowerShell 中检查 FTP 服务器上的文件是否存在

powershell - 尝试将 powershell 脚本转换为 VBscript