2016-11-18 131 views
1

我嘗試向我的函數引入一個可選的字符串參數。 Based on this thread should[AllowNull()]這樣做,但PowerShell仍然使用空字符串填充我的參數(使用PowerShell版本5.1.14393.206)。可選字符串參數(應爲NULL)

下面的函數說明了這個問題:

function Test-HowToManageOptionsStringParameters() { 
    Param(
     [Parameter(Mandatory)] 
     [int] $MandatoryParameter, 
     [Parameter()] 
     [AllowNull()] 
     [string] $OptionalStringParameter = $null 
    ) 

    if ($null -eq $OptionalStringParameter) { 
     Write-Host -ForegroundColor Green 'This works as expected'; 
    } else { 
     Write-Host -ForegroundColor Red 'Damit - Parameter should be NULL'; 
    } 
} 

爲了品牌認爲更糟糕的是,即使這個代碼不工作(分配$null進行測試參數),我真的不明白爲什麼這是不工作...

function Test-HowToManageOptionsStringParameters() { 
    Param(
     [Parameter(Mandatory)] 
     [int] $MandatoryParameter, 
     [Parameter()] 
     [AllowNull()] 
     [string] $OptionalStringParameter = $null 
    ) 

    $OptionalStringParameter = $null; 

    if ($null -eq $OptionalStringParameter) { 
     Write-Host -ForegroundColor Green 'This works as expected'; 
    } else { 
     Write-Host -ForegroundColor Red 'Damit - Parameter should be NULL'; 
    } 
} 

回答

1

好像,如果你把它分配給$null如果其申報爲被分配一個空字符串到您的變量。

你可以通過避開類型[string]$OptionalStringParameter。另一種方法是在if語句中檢查[string]::IsNullOrEmpty($OptionalStringParameter)

0

你的代碼改成這樣:

function Test-HowToManageOptionsStringParameters() { 
PARAM(
    [Parameter(Mandatory)] 
    [int] $MandatoryParameter, 
    [Parameter()] 
    [AllowNull()] 
    [string] $OptionalStringParameter 
) 

if(-not $OptionalStringParameter) { 
    Write-Host -ForegroundColor Green 'This works as expected'; 
} 
else { 
    Write-Host -ForegroundColor Red 'Damit - Parameter should be NULL'; 
} 
} 

二者必選其一!-not操作員檢查空。如果認爲問題是你的鍵入了參數 - >你在這個answer的評論中找到了一個解釋。

希望可以幫到