我如何从 cmd 执行此 PowerShell 命令?

How do i execute this PowerShell command from cmd?

也就是说,脚本应该提供 license2.txt 然后 powershell 应该过滤单词 name | Key material 但是我无法执行命令 电源外壳

(Get-content .\Licence2.txt) -replace "(</name|</keyMaterial )", "" >Licence.txt

为了从 cmd.exe / 批处理文件执行 Windows PowerShell 命令,您需要调用前者的 CLI,powershell.exe,记录在 about_PowerShell.exe (for PowerShell (Core) v6+, it is pwsh.exe - see about_Pwsh).

将任意 PowerShell 命令从 cmd.exe 传递到 powershell.exe 的一般方法是:

  • 将命令包含在 "..." overall 中,并将该字符串传递给 -Command-c) 参数(这是 powershell.exe 隐含的 参数,但请注意 pwsh.exe 现在默认为 -File (-f) , 所以最好是明确的)。

  • 将属于命令一部分的任何 " 字符转义\"[1 ],或者,如果可行,完全避免嵌入式 " 引用,并使用不需要的嵌入式 '...' 引用(verbatim PowerShell 字符串)完全在 "..." 内逃脱。

因此,在您的情况下:

powershell -c "(Get-Content .\Licence2.txt) -replace '</name|</keyMaterial ' > Licence.txt"

请注意,我从传递给 -replace 运算符的正则表达式中省略了不必要的 (...),以及不必要的 "" 替换操作数(替换与空匹配的内容字符串是 默认 ).

此外,最好在 -Command (-c) 或 -File (-f) 参数前加上 -NoProfile,以便抑制 profile files 不必要的和可能引起副作用的加载,这些加载主要用于 interactive 会话。


[1] 如果失败(如果 \" 分隔符之间的字符包含 cmd.exe 元字符,例如 &| ),将 "^""powershell.exe 结合使用,将 ""pwsh.exe 结合使用。