【问题标题】:Using PowerShell command and backtick newline inside Windows batch在 Windows 批处理中使用 PowerShell 命令和反引号换行符
【发布时间】:2017-11-09 04:21:34
【问题描述】:

我正在尝试编写一个 Windows 批处理文件,它将用中间的换行符替换出现的尖括号 (>

我是 PowerShell 新手,但在搜索可能的解决方案时,我发现了 PowerShell 的以下作品:

(get-content input.txt) -replace "><", ">`n<"  | set-content output.txt

要在 Windows 批处理中使用它,我需要将它包装在里面

    powershell -command "arguments"

所以最后的命令是这样的:

powershell -command "(gc input.txt) -replace '><', '>`n<'  | sc output.txt"

但是,这当然不起作用,因为替换文本周围的单引号会导致严重的引号转义字符被逐字处理。

我已经广泛搜索了用于允许识别 PowerShell 转义字符的转义字符的正确组合,并找到了类似的答案in here,但是当我尝试这个建议时,我得到一个“

【问题讨论】:

标签: windows powershell escaping


【解决方案1】:

查看 powershell.exe 命令行选项。您可以使用脚本块:

powershell -command {(gc input.txt) -replace "><", ">`n<"  | sc output.txt}

【讨论】:

  • 如果您已经在 PowerShell 中,则只能使用 scriptblock 参数;命令提示解释器不知道 PowerShell 脚本块是什么,这在批处理文件中不起作用,并尝试运行 sc.exe 来管理服务。
【解决方案2】:

避免使用转义字符和双引号?

powershell -command "(gc d:\t\input.txt) -replace '><', ('>'+[char]10+'<')  | sc d:\t\output.txt"

【讨论】:

    【解决方案3】:

    我已经解决了这个问题。 我也使用了延迟扩展,所以最后的命令是:

    powershell -Command "(gc !inputfile!) -replace (\"^>^<\", \"^>`n^<\")  | sc !outputfile!"
    

    所以它实际上使用了三种不同类型的转义字符! \ 和 ^ 和 ` 的组合。

    我希望我可以说我在逻辑上解决了它,但最后这只是在 ><.> 上使用不同转义符的随机尝试

    但现在这是一个很好的参考,说明如何在 Windows 批处理中使用 PowerShell,而不使用将转义字符转换为文字的单引号。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多