TechGuyTJ
TechGuyTJ

Reputation: 128

in Powershell how can I convert int32 to System.Nullable[int]

I am getting a type conversion error in my PowerShell function. the Function is using a web API to get the information back but my PowerShell function receives the info as 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

Upvotes: 0

Views: 2330

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174690

As pointed out in the comments, you've declared $vlan to be of type [int[]] - that is, an array of Int32's.

Just change the parameter declaration to [int]$vlan = $null and you should be fine.


Additionally, your if(){}else{} constructs can be much simpler.

For $vlan, just do $([bool]$vlan), a value of 0 will default to $false.

For the $DHCPType you can do the same, or use [string]::IsNullOrEmpty() to see if the user actually passed any argument: $(-not [string]::IsNullOrEmpty($DHCPType))

Upvotes: 1

Related Questions