Take Your Next Step With PowerShell

I just got back from Boston where I had a great time at the fall VMUG UserCon, presenting on PowerShell and PowerCLI. Regardless of what the title was, the message  behind the presentation was that everyone can become effective with PowerShell and hopefully some of these building blocks help you along the way.

One thing I hadn’t fully thought through before is that not everyone out there has development background. Talking about code with a room full of Systems Engineers finally helped me to realize this.  A couple of techniques came up in conversation that I know helped me take steps with my coding, and obviously hold interest for others who are getting started, so that’s what I’d like to talk about today. I’ve got a little bit of squirrel syndrome today and I see a shiny thing, so let’s go!

Expressions and sub-expressions

I’ve been using these for years, but I honestly had to go back and look up the name for this technique. Expressions harken back to mathematically expressions. Essentially by wrapping statements or an object in parentheses, you are telling the PowerShell engine to process the commands as a group. It’s essentially telling PowerShell about order of operations. Nothing too fancy about that.

What I find really fun with expressions is that they allow you to access properties of the group inline within your script. Take this code for example

$InputFile = "C:\Temp\linux_servers.json"

$Servers = $(Get-Content $InputFile -Raw | ConvertFrom-Json).Servers
 After reading in the contents of the json file, we directly reference the Servers array from the file, rather than individually parsing the elements of the file. Remember that PowerShell is all about objects by wrapping Get-Content $InputFile -Raw | ConvertFrom-Json in a $( ) we can directly access the Servers attributes of the object represented within $( ).
Here’s another little example that takes it a bit farther. It’s long so I could use backticks (I’ll get to that in a few) to make it a little more readable, but I want you to see this code in all it’s glory!
 if($($agents.data[$i].hostname.tolower()).substring($agents.data[$i].hostname.tolower().indexof("\") + 1,2) -eq $serverData.Hostname.ToLower().substring(0,2))]
Super fun right? Not all that readable, so let’s break it down:
$($agents.data[$i].hostname.tolower()).substring(...)
We use the $i variable (getting updated in a loop we don’t have here) this to index through an array of $agents.data[$i]. We are accessing the hostname element and use the tolower() method to cast it for comparison. Finally we use our handy dandy $() expression to take this output and then we can use that property to parse the substring. The point of this giant example is that you can take multiple different elements, do operations inline and use the output directly via expressions.
If I didn’t do this justice for you, please check out the PowerShell blog, SS64, or Mr. Jeff Hicks author of PowerShell Scripting and Toolmaking for more information.

Functions

I’ve been known to write dirty code. What I mean is that, I don’t always need the prettiest code, or the most denormalized or code that conforms to style guides. My whole reason for writing, is to make things more efficient and that sometimes results in “dirty code”. That being said, I have a growing love affair with functions. This isn’t a coding primer, so I’ll let the SS64 & Scripting guys teach you about the nuance of a function, but essentially it’s a named piece of code that you can call from some other piece of code. Why would you want to do this? It makes your code more modular. If your code is more modular, you can reuse it more places. If you can reuse it more places you can do more faster. If you can do more faster: PROFIT!

Anyways here’s an example I did for VMworld (with a touch of here-string help from my friends).  Here-strings… sounds like another post…

$cred=Get-Credential
$Guest = Get-VM -Name "Sql01"
$DiskSize = 40
$Disk = "Hard Disk 2"
$Volume = "D"

Invoke-VMScript -vm $Guest -ScriptText "Get-PSDrive -Name $volume" -ScriptType PowerShell -GuestCredential $cred

$objDisk = Get-HardDisk -VM $Guest -Name $disk
$objDisk | Set-HardDisk -CapacityGB $DiskSize -Confirm:$false
$scriptBlock = @"
echo rescan > c:\Temp\diskpart.txt
echo select vol $Volume >> c:\Temp\diskpart.txt
echo extend >> c:\Temp\diskpart.txt
diskpart.exe /s c:\Temp\diskpart.txt
"@
Invoke-VMScript-vm $Guest-ScriptText $scriptBlock-ScriptType BAT -GuestCredential $cred

Invoke-VMScript -vm $Guest -ScriptText "Get-PSDrive -Name $volume" -ScriptType PowerShell -GuestCredential $cred
This very simple code example will use invoke-vmscript to extend the drive on a windows machine. Now consider the following code:

if($Guest.Staaatus -ne "GuestToolsRunning" ){

Write-Host"Too bad so sad, you'll have to manually extend the OS partition. Maybe you should fix VMtools..."-BackgroundColor White -ForegroundColor DarkRed
}
else {
Set-OSvolume$Guest$Volume$Credential
}
}

### Function to Extend OS Volume
function Set-OSvolume{
Param(
$Guest,
[string[]]$Volume,
[System.Management.Automation.CredentialAttribute()]$Credential
)
$scriptBlock=@"
echo rescan > c:\Temp\diskpart.txt
echo select vol $Volume >> c:\Temp\diskpart.txt
echo extend >> c:\Temp\diskpart.txt
diskpart.exe /s c:\Temp\diskpart.txt
"@

Invoke-VMScript-vm $Guest-ScriptText $scriptBlock-ScriptType BAT -GuestCredential $cred>$null
$(Invoke-VMScript-vm $Guest-ScriptText "Get-PSDrive -Name $volume"-ScriptType PowerShell -GuestCredential $cred).ScriptOutput
}

Now that we’ve taken that same code snippet and turned into a function, our code got cleaner, more modular and something something profit. OHH did someone say cleaner code?

Splatting

Formatting scripts for presentation, or blogs, or community posts and actually making the readable can be a challenge especially when you start getting long one-liners. While prepping for PowerCLI 201 (cough, top 10 session, cough) Mr Luc and I had a bit of a debate around readability. I’ve historically been a fan of of the back-tick ` method to have a command extend beyond a single line.  Here’s what that looks like:

2017-10-18 12_50_39-VMworld 2017 SER2614BU - PowerCLI 201_ Getting More Out of VMware vSphere PowerC
“kyle, what was I thinking using back-ticks?”   “I dunno man, but I see Luc shaking his head over there”
I’m OK admitting when I’m wrong, and while back-ticks may be good in some situations, in others they just look like crap. So enters the splat, or as my wife likes to call it “splatting the gui”. I’m not going to try and give a deep dive on that concept, as there are already a number of great articles out there: Don Jones, author of the Month of Lunches, Rambling Cookie Monster, the googs. Just as a real quick reminder, splatting is a way in which you can specify both the parameter and it’s assigned value within a hashtable. By using this splat hashtable, you can dramatically simplify the code and it’s readability… as with all things, in the appropriate situation.

With that reminder out of the way, what I wanted to talk about is the when/where of splatting, but first I think this picture shows you what I’m talking about in terms of simplified code..

2017-10-18 13_00_27-VMworld 2017 SER2614BU - PowerCLI 201_ Getting More Out of VMware vSphere PowerC
“See how pretty this looks now Scott.”   “whoa”
Here’s what I’m finding with splats: while they make code more readable in a presentation or a blog post, you probably don’t want to try and use them while working out a problem or a new cmdlet. If you’re going to use them in your code, you’ll probably want to figure out your use case and parameters first, then back into using a splat. Likewise I would suggest knowing your audience and their experience level. While talking about this subject in Boston the other day, I got a few blank stares. Even if it’s pretty, the code still has to be usable and that means readable as well.

Hopefully these quick tips help. I’ll have a few more bits and bobs from my Boston talk in the next couple of days!

Advertisements

Champlain Valley VMUG – Summer recap

Better late than never I wanted to provide some information to all of the CVVMUG’ers out there coming out of our successful June meeting.

First off another big thanks to our friend Matt Bradford (aka VMSpot) for his vRealize Operations presentation. Here are another couple of gems from Matt that may interest you further:

vmware-vsphere-6-5-host-resources-deep-dive-proof-copiesThe technical talks seem to be a big hit, so much so that we already have a community presenter lined up for October to talk a bit about DRS. To celebrate, we’ll be giving away a couple copies of the brand new Host Resources Deep Dive book. Mind blowing stuff. For a taste you should check out the recent Datanauts podcast featuring the authors and if you make it to VMworld, their Deep Dive sessions are a must attend.

Speaking of VMworld, as of this writing we are 62 days and counting until the kickoff. Please let us know if you’ll be attending. We’d like to do meetup or a happy hour or something. Also stay tuned, you may be able to find us working and/or presenting at the event. 😉

oct12_vmugSpeaking of conferences, you can find my DellEMC world recaps and thoughts here. And here is a bunch of info about VMware announcements and happenings from the event. Lastly, we talked a little bit about the fracas with VMUG and the newly announced Dell Technologies User Community, you can get another voice on that matter here.

Now that the business end is behind, we are trying to line up a BBQ social event for August, place and time TBD. While you’re penciling stuff in, circle October 12 on your calendar for our next Champlain Valley VMUG. We’re still working on a location, but we’ll have that for you soon!

Last and certainly not least, AJ Mike and I want to thank all of you, members and vendors alike for being involved. This is a community for all of us, and we really value all that you bring.

And don’t think that just because we have one speaker lined up for October doesn’t mean that you can’t also get up there. Mules are awaiting.

What is a VMUG?

vmw_vmug_logoUp here in the Champlain Valley we are getting ready for our summer VMUG meeting. While planning the other day someone asked me “What is a V. M. U. G.?” To which I responded “VMUG (pronounced “v-MUG) is…” and launched into a standard elevator, evangelist pitch. Almost immediately I regretted the canned response and started reflecting on what VMUG means to me. It really didn’t take long to reach a resolution to the question. What VMUG means to me can be summed up in a single word: Opportunity.

As I’m someone who wears everything on his sleeve, I’d like to let you know that I’ve been a VMUG leader for almost a year and have been a member and proponent of it since long before that. However long before I was a leader, VMUG offered opportunities to me that may not otherwise be available in Northern New England.

To start with, one of my first VMUG events was the opportunity to attend the UserCon in Boston. If you’ve never been to a UserCon, I suggest checking one out at your earliest opportunity. You have access to labs, technical presentations, fantastic keynotes, access to vendors and your peers! All for the low low price of Free! It’s essentially a miniature version of the big conferences held in Las Vegas, except they are regional and free.

UserCons are awesome but to me the true lifeblood of VMUG is the local communities. As I mentioned previously, I help run the Champlain Valley VMUG community. We hold local meetings 3-4 times a year where you can come to hear from your peers, vendors and industry leaders talk about what is happening in their industries, applications or local businesses. It’s a chance to network with folks in your area and learn about cutting edge tech. Your local meetings are also free, so there really just isn’t a good excuse for missing out.

IMG_3138
Is it a VMUG? p-VMUG? v-VMUG? I’m so confused…

Speaking of networking, did you know that the VMUG advantage membership now includes NSX!  On top of all the evaluation software you can get a discounted ticket to VMworld. Actually it’s the only discount that you can stack with the other discounts. If you’re going to VMworld, or planning on taking a VMware class/exam you should just buy an advantage pass, it literally pays for itself. Seriously, I know this sounds like a sales pitch, but let’s suppose you’re going to take the vSphere: Install Configure and Manage course, that’s around $4000. A VMUG advantage membership gets you 20% off right out of the gate. It’s a pretty good ROI. I’m just saying…

Earlier I mentioned networking, but in my mind this is one of the greatest opportunities that VMUG can afford. Thanks to my involvement with VMUG I’ve learned a ton, gained a ton of awareness of the IT ecosystem, met CEO’s and frankly been able to advance my career. Getting up on stage and presenting about PowerCLI, a topic I’m very passionate about, has helped me get over my fear of public speaking in addition to paying it forward.

Someone recently came up to me and said (to paraphrase) “thanks for your session on PowerShell. I really took it to heart and have been using it in my day to day since.” In all honesty I really couldn’t ask for more than that. By being involved with VMUG I’ve been able to learn, grow my skills, engage with industry leaders and help others. It may sound like a sales pitch, but really this $hit just sells itself.

As always, I’m happy to hear any feedback you may have. Until then, I hope to see you getting involved June 15, at the Champlain Valley VMUG summer meeting!