2016-11-18 134 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的评论中找到了一个解释。

希望可以帮到