[英]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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.