PowerShell gc缺少括号

时间:2019-03-07 09:50:04

标签: powershell batch-file

我有一个批处理脚本,该脚本调用powershell gc命令,但无法修复它。

这是实际的脚本:

powershell -Command "(gc 'C:\test\run.bat') -replace '_installdir_', 'C:\Program Files\MySoftware'| Out-File -encoding ASCII C:\test\run.bat"

因此,我的脚本只需将我的gc中指定的文件内的 installdir 单词更改为另一个字符串(C:\ Program ....)(因为输出内容相同) )。

它完美地工作,但是当我尝试使其通用以便重用时,我已经做到了:

powershell -Command "(gc '%1%') -replace '%2%', '%3%' | Out-File -encoding ASCII %1%"

无论何时执行它,无论我作为args传递什么,我都会遇到这个问题:

powershell -Command "(gc 'C:\test\run.bat231"
The string is missing the terminator: '.
+ CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : TerminatorExpectedAtEndOfString

在这种情况下,我的第一个参数是C:\test\run.bat,与先前版本中使用的参数相同。 我这样叫:

myscript.bat C:\test\run.bat aa bb

Obs .:我在第二个和第三个中放置了废话args,以便在第一个中找出问题。

但是我不知道为什么它不起作用,也没有从最后得到这个“ 231”的地方。

1 个答案:

答案 0 :(得分:2)

批处理中的后期参数没有后缀%。它只是%1%2,...而不是用于变量的%1%%2%,...。因此,%中的尾随%1%被解释为变量%(未定义)中的第一个%') -replace '%%%2%中的尾随%3%也是如此。

"(gc '%1%') -replace '%2%', '%3%' | Out-File -encoding ASCII %1%"
        ~~~~~~~~~~~~~~~ ~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                       ^      ^                               ^

在上面的字符串中,%1扩展为第一个位置参数(在您的情况下显然为C:\test\run.bat),而“变量” %') -replace '%%', '%和{ {1}}扩展为空字符串,仅保留上述示意图中%' | Out-File -encoding ASCII %所指示的数字。

从位置参数中删除结尾的^以解决此问题(您可能还想添加一个%,以在参数中添加双引号)

~
相关问题