Thursday, January 05, 2017

PowerShell: Argument Checking (string or object?) with GetType()

I wrote a routine that performs a file search on a server via Admin access (i.e. \\servername\e$\...). Anyway, I have a couple of other routines that use an "object" that represents a server. So in some cases, meaning I need a [non-string, object] "$server" and in other cases I need [string] "$serverName". And yes, I've named the arguments appropriately to differentiate them. However, I didn't have any enforcement [i.e. argument validation] on the type. And sure enough, I criss-crossed them at one point. For the purists in the room, I could have used PSCustomObject,but I'm not for simplicity sake.

Declarations...

$serverName = "server1"
$server = [ordered]@{"Name"="server1","ipAddress"="127.0.0.1"}

$serverName.GetType().FullName
Gives
System.String 
And
server.GetType().FullName
Gives
System.Collections.Specialized.OrderedDictionary
So a simple "if" comparison between $.GetType().FullName against System.String, allows me a simple sanity check that I using the appropriate argument.

No comments: