运行 来自 .bat 脚本的 Powershell 命令不起作用,但是当我在命令行中直接键入它时它起作用

Running Powershell command from .bat script doesn't work, however it works when I type it directly in Command Line

Powershell -Command "cat .\tmp.txt | %{$_ -replace '\D', ''}"

为什么 运行 以上来自 .bat 脚本的 Powershell 命令不起作用? 只有当我直接在命令行中输入它时它才有效...

来自 .bat 脚本的

运行 产生以下消息:

    Expressions are only allowed as the first element of a pipeline.
    At line:1 char:39
+ cat .\tmp.txt | {$_ -replace '\D', ''} <<<<
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ExpressionsMustBeFirstInPipeline

powershell /? 提供此帮助文本(在下方进行了修剪以仅显示相关文本)。

-Command
...
To write a string that runs a Windows PowerShell command, use the format:
    "& {<command>}"
where the quotation marks indicate a string and the invoke operator (&)
causes the command to be executed.

因此您的批处理文件 powrshell 行需要读取:

powershell -Command "&{ cat .\tmp.txt | ForEach-Object {$_ -replace '\D', ''} }"

(请注意您的命令周围的额外花括号,并且 % 被替换为 ForEach-Object