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.

2 comments:

Government Jobs in Punjab said...

I am really really impressed with your writing skills as well as with the layout on your blog.

uok bsc 1st year result 2021

anjani02 said...

Salesforce CPQ Training Online
Enroll in Salesforce CPQ training online to gain hands-on experience in managing quotes, product bundling, and approval workflows. Learn from certified experts with interactive live sessions.