[英]How to pass command-line arguments to a PowerShell ps1 file
多年來,我一直使用cmd/DOS/Windows
shell 並將命令行參數傳遞給批處理文件。 例如,我有一個zuzu.bat
文件,我在其中訪問%1
、 %2
等。現在, when I am in a Cmd.exe shell
調用PowerShell
腳本時,我想做同樣的事情。 我有一個腳本xuxu.ps1
(我已將 PS1 添加到我的 PATHEXT 變量中,並與 PowerShell 關聯的 PS1 文件)。 但無論我做什么,我似乎都無法從$args
變量中得到任何東西。 它的長度始終為 0。
如果我在PowerShell
shell 中,而不是cmd.exe
,它可以工作(當然)。 但我還不夠舒服,無法全職生活在 PowerShell 環境中。 我不想輸入powershell.exe -command xuxu.ps1 p1 p2 p3 p4
。 我想輸入xuxu p1 p2 p3 p4
。
這可能嗎?如果可以,怎么做?
我無法開始工作的樣本是微不足道的,foo.ps1:
Write-Host "Num Args:" $args.Length;
foreach ($arg in $args) {
Write-Host "Arg: $arg";
}
結果總是這樣:
C:\temp> foo
Num Args: 0
C:\temp> foo a b c d
Num Args: 0
c:\temp>
這篇文章有幫助。 特別是本節:
-文件
在本地范圍內運行指定的腳本(“dot-sourced”),以便腳本創建的函數和變量在當前會話中可用。 輸入腳本文件路徑和任何參數。 File 必須是命令中的最后一個參數,因為在 File 參數名稱之后鍵入的所有字符都被解釋為腳本文件路徑,后跟腳本參數。
IE
powershell.exe -File "C:\myfile.ps1" arg1 arg2 arg3
表示運行文件 myfile.ps1 和 arg1 arg2 和 arg3 是 PowerShell 腳本的參數。
在深入研究 PowerShell 文檔后,我發現了一些關於此問題的有用信息。 如果您在文件開頭使用了param(...)
,則不能使用$args
; 相反,您將需要使用$PSBoundParameters
。 我將您的代碼復制/粘貼到一個 PowerShell 腳本中,它在 PowerShell 版本 2 中可以正常工作(我不確定您遇到此問題時使用的是哪個版本)。
如果您使用的是$PSBoundParameters
(並且僅當您在腳本開頭使用param(...)
時才有效),那么它不是一個數組,它是一個哈希表,因此您需要使用它來引用它鍵/值對。
param($p1, $p2, $p3, $p4)
$Script:args=""
write-host "Num Args: " $PSBoundParameters.Keys.Count
foreach ($key in $PSBoundParameters.keys) {
$Script:args+= "`$$key=" + $PSBoundParameters["$key"] + " "
}
write-host $Script:args
當調用...
PS> ./foo.ps1 a b c d
結果是……
Num Args: 4
$p1=a $p2=b $p3=c $p4=d
好的,首先這是破壞 PowerShell 中的一個基本安全功能。 有了這種理解,您可以這樣做:
您可能還想在其中放置一個-NoProfile
參數,具體取決於您的配置文件的用途。
您可以在文件中聲明參數,例如 param:
[string]$param1
[string]$param2
然后像這樣調用 PowerShell 文件.\temp.ps1 param1 param2....param10
等。
也許您可以將 PowerShell 調用包裝在.bat
文件中,如下所示:
rem ps.bat
@echo off
powershell.exe -command "%*"
如果隨后將此文件放在PATH
中的文件夾下,則可以像這樣調用 PowerShell 腳本:
ps foo 1 2 3
但是,引用可能會有點混亂:
ps write-host """hello from cmd!""" -foregroundcolor green
如果您想從 cmd 調用 ps1 腳本並傳遞參數而不調用腳本,例如
powershell.exe script.ps1 -c test
script -c test ( wont work )
您可以執行以下操作
setx PATHEXT "%PATHEXT%;.PS1;" /m
assoc .ps1=Microsoft.PowerShellScript.1
ftype Microsoft.PowerShellScript.1=powershell.exe "%1" %*
這是假設 powershell.exe 在您的路徑中
https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/ftype
您可能不會像看起來那樣得到“xuxu p1 p2 p3 p4”。 但是當你在 PowerShell 中並且你設置
PS > Set-ExecutionPolicy Unrestricted -Scope CurrentUser
您可以像這樣運行這些腳本:
./xuxu p1 p2 p3 p4
或者
.\xuxu p1 p2 p3 p4
或者
./xuxu.ps1 p1 p2 p3 p4
我希望這能讓您對 PowerShell 更加熟悉。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.