直接用 Windows PowerShell 运行 打开命令文件

Open a command file with Windows PowerShell running it directly

我想制作一个包含 Windows Powershell 命令的文件。然后我想直接用 windows powershell 打开它,而不按我想要的任何键 windows powershell start 运行 这些命令直接与命令提示符相同我可以制作 .cmd 或 .bat 文件。

例如: 这是两个命令或Powershell,我想保存这个文件。然后我想通过powershell直接执行这个文件。我也尝试将其另存为 ps1ps2 扩展名,但无法正常工作。网上很多方法都不行。有什么解决办法吗?

我找到了解决办法。我使用command powershell.exe 可以在cmd中直接执行powershell命令。 powershell.exe $MyVariable=Get-Content .\Path.txt 对我来说工作正常

  • 所有版本的 PowerShell 脚本文件都使用 .ps1 文件扩展名。

  • PowerShell 中,您可以直接调用它们,例如.\script.ps1

    • 请注意,与 cmd.exe 不同,您 必须 使用 .\(或完整路径)才能执行位于 当前目录 - 仅 script.ps1 不起作用 - 请参阅 了解背景信息。
  • cmd.exe 开始,您必须使用 PowerShell 的 CLI(PowerShell [Core] v6+ 中的powershell.exe in Windows PowerShell / pwsh)才能执行脚本文件:

    • powershell.exe -File script.ps1
    • pwsh -File script.ps1-File可省略)

请注意 -File .\ 前缀是 不需要

但是,如果您改用 -Command (-c)(这是 默认值 powershell.exe,而 pwsh 现在默认为 -File),你 do 需要 .\,因为 -Command 参数被解释为 一段 PowerShell 代码,即就像您在 PowerShell 会话中提交它一样。

您发现了这个 ,您在其中将 PowerShell 命令直接 传递给(隐含的)-Command 参数。

但是请注意,最好双引号这样的命令,以防止cmd.exe解释某些字符本身,中断通话。

例如,如果您没有在 "..." 中包含 -Command (-c) 参数,则以下调用将会中断:

# From cmd.exe; "..." required.
C:\>powershell.exe -c "Write-Output 'a & b'"
a & b

另一个重要的考虑因素是您需要转义 embedded " 字符。作为 CLI 的 \"(即使 PowerShell- 内部 你会使用 `"""):

# From cmd.exe; note the inner " escaped as \"
C:\>powershell.exe -c "Write-Output \"hi there\""
hi there