Category Archives: PowerShell

Retrieve CDP/LLDP info

Search for an easy way to get CDP/LLDP info for any given ESXi physical port (vmnic)? Here it is!
It relies on ObnTransformation from my previous post and also depends on PowerShell Community Extensions for ?? alias (Invoke-NullCoalescing). You can replace the latter with the simple if in case you don’t have PSCX installed.
Keep in mind that (some) devices return MAC instead of the management IP in LLDP info.
By default all vmnics are queried.


OBN (Object By Name) transformation

You might have known that most of PowerCLI cmdlets parameters accept objects or object names (with wildcard characters allowed). Take a look at New-VM cmdlet: you can pass strings to VMHost, ResourcePool, Datastore, etc. parameters as well as the objects itself. Or maybe you’ve even never noticed this since it just works!
Want the same behavior for your own functions? No problem! Use the function below to perform transparent transformation from any eligible object to the object you need (View or Impl). The neat feature it has is limiting the retrieved properties for view object, what considerably improves performance in some cases.

This is how to integrate it to your own function:

The one thing you should be aware of is that it accepts wildcards, while you may think the regular expressions are more powerful tool (and I completely agree with you). The reason I had in mind was to not to confuse users who got used to the default PowerCLI behavior. It’s up to you to remove ConvertTo-Regex part from -Filter parameter in Get-View call. But in this case sometimes you might be puzzled when the script can’t find an object with the name you are hundred percent sure exists. Doh! Any braces in the name? Use [regex]::Escape() to escape them.

Manage Zip archives with PowerShell

I know there are lots of examples and function implementations out there (for instance, the one from jaykul), nonetheless I’d like to add my 2 cents. Even 5c, since my version is more powerful It allows you to set compression level, append/replace files to/in existing archives and extract only necessary files from archive.
For instance, to extract vmware.xml file from the archive’s root and all the files from the vib folder stored in root also (yep, we’re expanding, creating subfolder in the current directory (replacing if already exists), you need to run the following command:
Extract-ZipFile -ZipFilePath -FilesToExtract vmware.xml,vibs/ -CreateSubfolder -Force
The slash character indicates that you’d like to expand the folder, not the file.



MySQL database manipulation from PowerShell

Download MySQL Connector/NET first.


Tuning your ISE

After being silent for a while it’s time to explode with some really great stuff!
Let’s start with the environment you develop the scripts in. There are several options out of there: free PowerGUI – very popular IDE but doesn’t look nice for me, Sapiens PowerShell Studio – seems to be a powerful tool but costs 389$ at the moment. So I look back to the ISE that is bundled with WMF 4.0. Some vital features missing, so we need to put in an effort to fill the blanks. But it’s not as hard as you might think. That’s the way to go!

The first step is to customize your profile, which is loaded every time you start the ISE. The $profile variable will suggest you the file location. Begin with filling the file by adding the necessary paths to $Env:Path variable, eg:
$env:Path += ';C:\Program Files (x86)\EMC\Navisphere CLI;'
There is another way to modify environment variables. For instance, this is how to add the path where ISE will search for modules:
[System.Environment]::SetEnvironmentVariable('PSModulePath',$env:PSModulePath + ";$ModuleDir",'Machine')
Then you can Import all necessary modules and snap-ins, though in the recent PoSh versions they are auto-loaded.

You can hide the default snippets
$psISE.Options.ShowDefaultSnippets = $false
and import your own ones. If you wrapped them into the module, run this:
Import-IseSnippet -Module PurpleScreen

To keep the help docs up to date (say, max 4-weeks old), check the file, where the last help update date stored, and run Update-Help if necessary:

The next step is to take care of storing passwords in an easy yet secure way, so you have an access to them once ISE started. Windows provides you with the all necessary tools. First, execute the line below and enter your password. That will store the encrypted password string in the $PassDir folder (needs to be done only once). Windows handles the private key, which is your ‘profile’, thus the password can be decrypted only after you are authenticated.

Then you can load the password in the current session and compile the Credential object:

Text processing
Next is to add some text-processing capabilities for some reason missing in the standard bundle and expose them with hotkey combinations (the functions’ source code will be revealed in the next blog posts introducing my module). You may change hotkeys at your discretion, but keep in mind that some of them are already occupied with built-in ISE commands.

Since we are VMware guys (aren’t we?), we need a hotkey for setting PowerCLI properties and connecting to multiple vCenter/vCloud servers (a couple of VIProperties as a bonus):

Also you may need the certificate in hand to sign the scripts you write. If it’s been already imported in the cert store on your machine, just push it to the variable with:
$CodeSigningCert = gi Cert:\LocalMachine\my\<thumbprint>
To sign a script using the cert and publicly available timestamp server run
Set-AuthenticodeSignature -Certificate $CodeSigningCert -FilePath "$ScriptDir\PurpleScreen.psm1" -TimestampServer

Remote sessions
Need to connect to an interactive remote session / load cmdlets from remote session with a hotkey? That’s pretty easy (more on remote sessions, configurations, CredSSP, etc. in the separate post):

You can see some handling of opened tabs here. The main thing I was missing was keeping the session state between ISE reloads. I’d like to pick up the things from where I left off by auto-loading all opened tabs and files from my previous session. This part was successfully implemented with Save-ISEState and Load-ISEState functions (stay in touch for PurpleScreen module).

It will also show all currently available command shortcuts for convenience.

And in the end some really neat feature – GitHub integration! Press Ctrl+Alt+G to open GitHub tab with your project’s local repository (needs GitHub desktop app installed and repository configured)

That’s all for now!

Stay tuned and remember to follow the main rule – once written, share with a community!

Use all the power of PowerShell with NetCmdlets. Out of box you can: gain SSH access to ESXi 5.x hosts from PowerShell, work with multiple internet protocols (IMAP/POP/WebDAV/DNS/FTP/etc), deploy portable syslog server in seconds and much more.

Unfortunately community edition doesn’t support encryption-enabled cmdlets. To use SSH, SFTP you need to upgrade to paid version.

PowerShell scheduled job output redirection

Scheduling the script execution is rather common task. You might know that it’s possible to manage scheduled tasks in PowerShell with built-in ScheduledTask module cmdlets. To keep track whether the task run successfully or not it’s quite useful to redirect the output of the script to a file. PowerShell allows output redirection for all stream types (standard/error/warning/etc), see TechNet about_Redirection help topic.
To be able to run your scripts with -Verbose option you should leverage Advanced_Functions syntax (see another Core About topic). Just add couple of strings to the beginning of the script

and use Write-Verbose cmdlet throughout the script where chatty output is needed. At first glance it seems to be an easy task to combine all mentioned together, but in fact I saw lots of questions across the web where people struggled to make it work. Indeed it took much effort before I succeeded. I’ve tested many different configuration and most of them didn’t work for me too. That’s what I came up with and it worked for me:

Esxcli namespace tree

Every time a new ESXi version released I wonder what the functionality was added to esxcli. As you know all available namespaces and commands can be retrieved by typing esxcli command list in the console. To make the output look pretty I’ve written a couple of lines of PoSH code that generates the handy namespaces tree view.

The reason I’ve used the .NET class instead of Add-Content / Out-File cmdlets is that the latter append the new line.
Here is for the latest version 5.5.

OmniTracker automation

Few words outside the virtualization world yet PoSH scripting related.
I’ve been working for a while in the company that uses Omnitracker as a helpdesk and incident management solution. Using its web interface as well as thick client isn’t the best experience. And when it comes to do it on a regular basis it turns to a nightmare especially for a scripting guy like me. So what should we do in this situation? Yep, exactly! Automate it!
As others the first thing I’ve tried is to call Google for help. What was my surprise when I saw nothing relevant at all in the first few pages except the Linkedin profile of a guy who should have the desired skills. Wow, the power of social networks in action! Take a challenge!
Looking through the manuals I’ve stumbled on the doc describing the automation interface. Good catch! C# there, so the PoSH isn’t far away. It turned out simple enough and after few tries I’ve managed to get it work. Couple of functions produced can be found below. As Omnitracker heavily relies on cusmomization most likely you won’t find it working in your environment but this functions should give you a tip how to handle the objects in OT.