2017-02-24 48 views
2

我有一個簡單的腳本Set-StrictMode是否與參數塊不兼容?

Param([string] $myStringValue) 
echo $myStringValue 

當我與./test.ps1 -myStringValue steve調用它,它工作得很好。

但是,如果我添加設置StrictMode的開頭:

Set-StrictMode -Version Latest 
Param([string] $myStringValue) 
echo $myStringValue 

我收到以下錯誤:

> ./test.ps1 -myStringValue steve 
The variable '$myStringValue' cannot be retrieved because it has not been set. 
At D:\code\cadgraphics\test.ps1:2 char:20 
+  Param([string] $myStringValue) 
+     ~~~~~~~~~~~~~~ 
    + CategoryInfo   : InvalidOperation: (myStringValue:String) [], RuntimeException 
    + FullyQualifiedErrorId : VariableIsUndefined 

The variable '$myStringValue' cannot be retrieved because it has not been set. 
At D:\code\cadgraphics\test.ps1:3 char:10 
+  echo $myStringValue 
+   ~~~~~~~~~~~~~~ 
    + CategoryInfo   : InvalidOperation: (myStringValue:String) [], RuntimeException 
    + FullyQualifiedErrorId : VariableIsUndefined 

我已嘗試設置$myStringValue事先

$myStringValue = '' 
Set-StrictMode -Version Latest 
Param([string] $myStringValue) 
echo $myStringValue 

但只是讓它在Param塊上窒息:

Param : The term 'Param' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, 
verify that the path is correct and try again. 
At D:\code\cadgraphics\test.ps1:3 char:5 
+  Param([string] $myStringValue) 
+  ~~~~~ 
    + CategoryInfo   : ObjectNotFound: (Param:String) [], CommandNotFoundException 
    + FullyQualifiedErrorId : CommandNotFoundException 

我在做什麼錯?

+0

也許你可以將該參數標記爲強制,或將其初始化爲某些內容。 –

回答

7

我認爲問題在於param()需要首先(或僅在某些特殊語句之前)。在param()區塊後面輸入Set-StrictMode

您可以在ISE中看到此內容,因爲語法突出顯示將從深藍色(語句)變爲param()爲藍色(cmdlet /函數/表達式)。