在Powershell中如何将int32转换为System.Nullable [int]

时间:2015-06-24 21:01:24

标签: powershell

我在PowerShell函数中遇到类型转换错误。函数使用Web API来获取信息,但我的PowerShell函数接收信息为Int32。

function Get-NetworkInfo
{
    [CmdletBinding(SupportsShouldProcess=$True)]
    Param(
        [Parameter(ValueFromPipelineByPropertyName=$true)]
        [string[]]$NetworkAddress = $null,
        $Subnet = $null,
        [Parameter(ValueFromPipelineByPropertyName=$true)] 
        [int[]]$VLan = $null,
        [Parameter(ValueFromPipelineByPropertyName=$true)]
        [string[]]$NetworkName = $null,
        [ValidateSet("NONE", "ENTERPRISE", "BUILDINPLACE", "ENTERPRISE_WIFI")]
        [string]$DHCPType = $null
    )

    BEGIN
    {
        $url = "http://Server1:8071/DataQueryService?wsdl" 
        $proxy = New-WebServiceProxy -Uri $url 
    }
    PROCESS
    {
        $proxy.AdvancedDiscoveredNetworkSearch($networkAddress,$subnet,$vlan,$(if($vlan){$True}Else{$false}),$networkName,$dhcpType,$(if($dhcpType){$True}Else{$false}))
    }
    END
    {

    }
}

ERROR:

C:\Scripts> Get-NetworkInfo -vlan 505 Cannot convert argument "vlan", with value: "System.Int32[]", for "AdvancedDiscoveredNetworkSearch" to type "System.Nullable`1[System.Int32]": "Cannot convert the "System.Int32[]" value of type "System.Int32[]" to type "System.Nullable`1[System.Int32]"."
At C:\Get-NetworkInfo.ps1:23 char:163
+ ... pe){$True}Else{$false}))
+                    ~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

1 个答案:

答案 0 :(得分:1)

正如评论中所指出的,您已声明 0.00 90.00 3 . . . . . . 360.00 90.00 14 . . . . . . . . . 0.00 -89.00 9 . . . . . . 360.00 -89.00 14 0.00 -90.00 5 . . . . . . 360.00 -90.00 7 属于$vlan类型 - 即[int[]]&的数组 #39; S。

只需将参数声明更改为Int32即可。您应该没问题。

此外,您的[int]$vlan = $null构造可以更加简单。

对于if(){}else{},只需执行$vlan,值为0将默认为$([bool]$vlan)

对于$false,您可以执行相同操作,或使用$DHCPType查看用户是否实际传递了任何参数:[string]::IsNullOrEmpty()

相关问题