簡體   English   中英

通過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 

如果這對您來說是“不可接受的”,最簡單的方法是與ps1腳本(相同路徑)一起創建bat腳本並添加以下內容:

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

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

這將創建在cmd中任何地方調用腳本所需的包裝,因為可以從cmd執行批處理文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM