2015-06-24 39 views
0

我在PowerShell函數中遇到類型轉換錯誤。該函數正在使用Web API來獲取信息,但我的PowerShell函數以Int32的形式接收信息。在Powershell中如何將int32轉換爲System.Nullable [int]

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 
    { 

    } 
} 

錯誤:

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

什麼是你的問題?您正在傳遞數組'int []',其中'Nullable '是預期的。你可能不應該首先聲明它是數組。或者,如果您必須爲每個元素調用它,則循環數組。 – n0rd

+0

目的是接受一個數組,我只是沒有完成數組循環的邏輯。 – TechGuyTJ

回答

1

正如評論指出的那樣,你聲明$vlan[int[]]類型的 - 也就是說,一個陣列Int32的。

只是將參數聲明更改爲[int]$vlan = $null,你應該沒問題。


此外,您的if(){}else{}構造可以更簡單。

對於$vlan,只要做$([bool]$vlan),值0將默認爲$false

對於$DHCPType你可以做同樣的,或使用[string]::IsNullOrEmpty()來查看用戶是否實際傳遞任何參數:$(-not [string]::IsNullOrEmpty($DHCPType))

相關問題