通过 powershell 命令将 powershell 脚本放在路径上。

put a powershell script on path through powershell commands.

我有一个 powershell 脚本,我想通过将它放在路径中从 cmd/ps 任何位置 运行。 可以实现的命令是什么?

我基本上是在寻找一个 UNIX 等效项,将您的脚本放在 bashrc 中,因此可以从任何地方使用到 运行。

echo 'export PATH=$PATH:/path/to/script' >> ~/.bashrc && source ~/.bashrc

在 windows 中,您还有系统变量 PATH,用于定义可执行文件的位置。

假设您只使用 Powershell,您可以执行以下应该等效的操作:

$newPath = "c:\tmp\MyScriptPath"; 
[Environment]::SetEnvironmentVariable('PATH', "$($env:Path);$newPath", [EnvironmentVariableTarget]::User);
# Update the path variable in your current session; next time it's loaded directly 
$env:Path = "$($env:Path);$newPath";

然后您可以直接在 Powershell 中使用脚本名称执行脚本。

但是_ :这在 cmd 下不起作用,因为 cmd 不知道如何将 ps1 脚本作为可执行文件处理。通常人们会通过调用以下命令从 cmd 执行脚本:

 Powershell.exe -executionpolicy remotesigned -File  C:\Tmp\Script.ps1 

如果这 "unacceptable" 适合您,最简单的方法是创建一个 bat 脚本以及您的 ps1 脚本(相同路径)并添加以下内容:

Script.bat(假设您在同一文件夹中有 Script.ps1):

@ECHO OFF
PowerShell.exe -Command "& '%~dpn0.ps1'"
PAUSE

这将创建在您的 cmd 中的任何位置调用脚本所需的包装器,因为可以从 cmd 执行批处理文件