首页 > 解决方案 > .Replace 适用于 powershell 但不适用于批处理脚本

问题描述

我的批处理脚本如下所示:

@echo off
echo.
echo Replacing instances of type="module" in index.html with type="text/javascript"
cd www

(Get-Content index.html).Replace("module", "javascript") | Set-Content index.html

当我尝试在 powershell 中使用 .Replace 时,它​​工作正常,但是从批处理脚本运行它失败并出现错误.Replace("module" was unexpected at this time.

(Get-Content index.html) -replace 'module', 'javascript' | Set-Content index.html

也想出了同样的错误。提前感谢您的帮助。

标签: powershellbatch-file

解决方案


如果您真的想从 .bat 脚本调用 powershell,这里有一种方法。输出文件必须与输入文件不同。"> index2.html" 部分由 cmd 运行,因此它是用 ascii 编码的,而不是 unicode。

type index.html | powershell $input -replace 'module','javascript' > index2.html

或者将其完全保留在 powershell 中。文件编码将是“ansi”。

powershell "(get-content index.html) -replace 'module','javascript' | set-content index.html"

推荐阅读