【问题标题】:Powershell newline in script argument not working脚本参数中的 Powershell 换行符不起作用
【发布时间】:2021-05-05 17:11:15
【问题描述】:

我有这个小脚本,我用不同的正则表达式参数调用它来替换文件中的文本:

param ($file, $fnd, $rpl)

(Get-Content $file -Raw) -replace $fnd , $rpl | Set-Content $file

问题是如果我向它传递一个包含新行转义码 `r`n 的参数,如下所示:

powershell -File txt-replace.ps1 "file path" "RegEx_pattern" "line1`r`nline2"

将写入文件:

line1`r`nline2

而不是:

line1
line2

但是,如果我在脚本中定义 $rpl,并使用确切的参数内容,它就可以工作:

$rpl = "line1`r`nline2"

写道:

line1
line2

如果我在寡妇终端中作为命令运行它也可以:

powershell -command "(Get-Content file_path | Out-String ).Trim() | ForEach-Object {$_ -replace 'RegEx_pattern' , \"line1`r`nline2\"} | Set-Content file_path "

我在脚本中进一步调试了它:

write-host $rpl

在终端中写入:

line1`r`nline2

但是

$rpl= "line1`r`nline2"
write-host $rpl

在终端中写入:

line1
line2

我错过了什么?

【问题讨论】:

  • 改用-command --> powershell -command ".\txt-replace.ps1 \"file path\" \"RegEx_pattern\" \"line1rnline2\""。请记住反斜杠转义要传递给脚本参数的引号,因为您显然是从 PowerShell 以外的地方调用的。
  • 如果您使用的是 Windows 终端,是否可以使用 PowerShell 或 Windows PowerShell 窗口重新测试此方案?您似乎正在使用命令提示符。
  • 谢谢,使用 -command 可以,但解释是什么?
  • 在 Powershell winodw 中测试并且可以正常工作。但我需要通过第三方应用程序槽命令调用它
  • 使用-File,脚本参数在当前shell解释后按字面意思传递。 CMD 不知道换行符是什么。使用 -command 时,命令字符串被视为在 PowerShell 提示符下输入。

标签: string powershell escaping newline command-line-arguments


【解决方案1】:

使用-Command参数是最简单的。

powershell -Command  ".\txt-replace.ps1 \"file path\" \"RegEx_pattern\" \"line1`r`nline2\""

反斜杠转义用于 CMD shell。由于您希望将这些引号传递给 PowerShell,因此我们需要首先在 CMD shell 层对它们进行转义。否则,CMD 会认为它们是周围的字符串以供其解释。

当使用-File 时,脚本参数在当前shell 解释后按字面意思传递。 CMD 不知道换行符是什么,所以它们只是保持 `r`n,然后按字面意思作为字符串参数之一传递。

使用-Command 时,命令字符串被视为在 PowerShell 提示符下输入。

更多信息请参见About_PowerShell.exe

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 2018-02-15
    • 1970-01-01
    • 2021-11-06
    • 2020-04-12
    • 2020-05-31
    • 2021-12-20
    • 1970-01-01
    相关资源
    最近更新 更多