Powershell Set-Content 对一个文件失败而对另一个文件成功?

Powershell Set-Content fails for one file and succeeds for another?

尝试修改不同的文件并得到两种不同的结果。成功的文件“autoexec.cfg 工作正常。这是文件内容和 powershell 代码。 c:\temp\autoexec.cfg 包含:

disable_write_track = true
webgui_port = 8470

修改文件的powershell代码:

$WGP = get-random -minimum 8000 -maximum 8999
$line = Get-Content "C:\temp\autoexec.cfg" | Select-String webgui_port | Select-Object -ExpandProperty Line
$content = Get-Content "C:\temp\autoexec.cfg"
$content | ForEach-Object {$_ -replace $line,"webgui_port = $WGP"} | Set-Content "C:\temp\autoexec.cfg"

失败的文件是这样设置的。 c:\temp\serverSettings.lua 包含:

cfg = 
{
    ["port"] = 10302,
} -- end of cfg

修改文件的powershell代码

$DCSP = get-random -minimum 10000 -maximum 19999
$line = Get-Content "C:\temp\serverSettings.lua" | Select-String port | Select-Object -ExpandProperty Line
$content = Get-Content "C:\temp\serverSettings.lua"
$content | ForEach-Object {$_ -replace $line,"    [\`"port\`"] = $DCSP,"} | Set-Content "C:\temp\serverSettings.lua"

文件不会改变,除非它改变了。我在 Notepadd++ 中打开文件,在 运行 代码 Notepad++ 看到文件已更改并想重新加载但没有任何更改。

-replace是正则运算符,[]是正则表达式中的特殊结构,需要适当转义。

最简单的方法是 [regex]::Escape():

$content | ForEach-Object {$_ -replace [regex]::Escape($line),"    [\`"port\`"] = $DCSP,"} | Set-Content "C:\temp\serverSettings.lua"