[英]What does hyphen/dash parameter mean to PowerShell?
我發現,如果僅在Windows 10上將破折號傳遞給PowerShell 5.1腳本的參數,例如:
powershell.exe -File Test.ps1 -
我收到一條奇怪的錯誤消息:
C:\\ path \\ Test.ps1:無法處理參數,因為參數“名稱”的值無效。 更改“名稱”參數的值,然后再次運行該操作。
- CategoryInfo:InvalidArgument:(:) [Test.ps1],PSArgumentException
- FullyQualifiedErrorId:Argument,Test.ps1
Test.ps1
僅是:
echo "foo"
我遇到的實際問題是,當腳本聲明任何強制性參數時:
param (
[Parameter(Mandatory)]
$value
)
echo "foo"
然后以相同的方式(使用-
參數)執行腳本完全沒有執行任何操作。 無輸出。 沒有錯誤訊息。 它只是掛了幾秒鍾。 然后控件返回到命令提示符。
C:\path>powershell.exe -File Test.ps1 -
C:\path>_
-
對PowerShell(5.1)意味着什么?
相反,在Windows 7上使用PowerShell 2.0,在這種情況下,我可以使用腳本:
C:\path>powershell.exe -File Test.ps1 -
Test.ps1 [-value] <Object> [-Verbose] [-Debug] [-ErrorAction <ActionPreference>] [-WarningAction <ActionPreference>] [-ErrorVariable <String>] [-WarningVariable <String>] [-OutVariable <String>] [-OutBuffer <Int32>]
C:\path>_
有什么意義(缺少必需的參數)。
在沒有強制性參數聲明的情況下,腳本可以工作(將其打印輸出):
C:\path>powershell.exe -File Test.ps1 -
foo
C:\path>_
這不是答案,但我也很好奇。 如果您已經知道了,我會對您發現的內容感興趣。 否則,如果有幫助, Powershell -h
說-file
之后的所有內容都是腳本以及傳遞給它的所有參數。
-File
Runs the specified script in the local scope ("dot-sourced"), so that the
functions and variables that the script creates are available in the
current session. Enter the script file path and any parameters.
File must be the last parameter in the command, because all characters
typed after the File parameter name are interpreted
as the script file path followed by the script parameters.
令牌生成器將其作為CommandArgument讀入。
Powershell >> $Errors = $Null
Powershell >> [System.Management.Automation.PSParser]::Tokenize("powershell -file test.ps1 -", [ref]$Errors)[3]
Content : -
Type : CommandArgument
Start : 26
Length : 1
StartLine : 1
StartColumn : 27
EndLine : 1
EndColumn : 28
因此,問題似乎更進一步,但我找不到一種簡單的方法來調用Parser函數進行測試。
我確實看到有一種情況不應該發生 ,即錯誤被吞沒並返回null,這可能導致它像您的示例一樣停止運行
該行為應被認為是一個錯誤 -開頭為-
但不是有效的參數名稱,應將其作為位置參數傳遞,而不是報告錯誤。
該錯誤影響:
Windows PowerShell(從v5.1.18362.145起)-尚不清楚是否會進行修復。
... the value of argument "name" is not valid ...
)或(b) -
是否被靜默忽略取決於您的參數是否具有參數屬性,例如作為[Parameter(Mandatory)]
[1]和/或您的param()
塊具有[CmdletBinding()]
屬性(如果是,則(b)適用)。 PowerShell Core 6.x-即,該問題將在v7中解決 (撰寫本文時為最新版本:v7.0.0-preview.3); 我不知道6.2.2(即撰寫本文時的最新穩定版本)是否將得到修復-我們將在您提交的GitHub上查看錯誤報告的情況。
至於解決方法 (在PowerShell Core中類似地工作):
使用-Command
而不是-File
。
盡管這改變了命令行解析的語義[2] ,但在這種簡單情況下,區別並不重要:
C:\> powershell -Command ./Test.ps1 - # note the "./"
請注意./
,因為使用-Command
( -c
)使PowerShell像解析PowerShell代碼一樣對參數進行解析,並且按文件名重新執行腳本的通常限制僅適用-Command
(為防止意外執行當前目錄中的文件,您可以需要一個路徑組件來明確表示該意圖,因此需要前綴./
或.\\
)。
如果您的腳本文件路徑需要用引號引起來,則必須使用引號並在&
前面加上呼叫操作符; 例如:
C:\> powershell -Command "& \"./Test.ps1\" -"
[1]在聲明的參數上添加[Parameter()]
屬性會隱式使封閉的腳本/函數成為高級腳本/函數,在這種情況下,將應用不同的解析規則。 [CmdletBinding[]
上應用到param(...)
塊的[CmdletBinding[]
屬性將腳本/函數顯式標記為高級。
[2]見這個答案對於如何之間的差異-File
和-Command
參數解析。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.