powershell - Parameter value can't be set to null if data type is set -


i finished typing out long question, figure out answer on own right before posted. however, still not perfect solution , wondering if explanation why following won't work.

what want have optional parameter, if not set, null. parameter string.

so this:

function myfunction {     param([string]$x = $null)     set-aduser -identity someuser -officephone $x } 

by doing that, seems $x can never null, if explicitly set later in code. if remove [string], works fine. wondering why be. it's not big deal, can't see why wouldn't work.

this because casting parameter value string:

param([string]$x = $null)       ^^^^^^^^ 

casting $null string returns empty string:

ps > [string]$x = $null ps > $x.gettype()   ispublic isserial name                                     basetype                 -------- -------- ----                                     --------                 true     true     string                                   system.object              ps > $x.length 0 ps > 

one way around remove cast , check type of variable using -is operator:

function myfunction {     param($x)     if ($x -is [string] -or $x -eq $null) {         set-aduser -identity someuser -officephone $x     } } 

you should output error if user passes argument of wrong type or else function apparently nothing, can confusing.

buy if doing this, should ask if not better have set-aduser output error you. more efficient, involve less code, , produce same result.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -