繁体   English   中英

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

[英]Open a command file with Windows PowerShell running it directly

我想制作一个包含 Windows Powershell 命令的文件。 Then I want to open it with windows powershell directly and without pressing any key I want windows powershell start running those commands directly same as command prompy I can make.cmd or.bat file.

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

在此处输入图像描述

  • PowerShell 脚本文件,在所有版本中,使用.ps1文件扩展名。

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

    • 请注意,与cmd.exe不同,您必须使用.\ (或完整路径)才能执行位于当前目录中的文件 - 只是script.ps1不起作用 - 有关背景信息,请参阅此答案
  • From cmd.exe , you must use PowerShell's CLI ( powershell.exe in Windows PowerShell / pwsh in PowerShell [Core] v6+ ) in order to execute a script file:

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

请注意,使用-File不需要. .\ -前缀。

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

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

但是请注意,最好将此类命令用双引号引起来,以防止cmd.exe本身解释某些字符,从而中断调用。

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

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

另一个重要的考虑因素是您需要为 CLI 转义嵌入" chars. as \" (即使 PowerShell- 在内部您将使用`""" ):

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM