Parameter value cannot be set to null if data type is specified

I just finished typing a long question just to figure out the answer on its own before I posted a post. However, this is not a perfect solution yet, and I'm wondering if I can explain why the following won't work.

What I want to do is have an optional parameter which, if not set, will be null. I would like this parameter to be a string.

So, I would do something like this:

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


In doing so, it seems like $x

it can never be null, even if I explicitly set it later in the code. If I removed [string]

it works fine. Just wondering why that would be. It doesn't matter, but I don't understand why it won't work.


source to share

1 answer

This is because you are passing the parameter value to a string:

param([string]$x = $null)


Casting $null

to string always returns an empty string:

PS > [string]$x = $null
PS > $x.GetType() 

IsPublic IsSerial Name                                     BaseType                
-------- -------- ----                                     --------                
True     True     String                                   System.Object           

PS > $x.Length
PS >


One way to get around this is to remove the cast and check the type of the variable yourself using -is


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


Then you should also throw an error if the user passes in an argument of the wrong type, otherwise the function doesn't seem to do anything, which can be confusing.

Buy, if you are already doing all of this, you have to ask yourself if it might not be better to have an Set-ADUser

error output for you. It would be more efficient, involve less code, and end up with the same result.



All Articles