Expand RDM in virtual compatibility mode

As opposed to the physical RDM mode with the virtual one after expanding the LUN on the storage array side and rescanning HBA vm still can’t see the increased capacity. The official VMware tutorial says to shutdown vm and re-add RDM. This isn’t acceptable. The hint to make it happen with no downtime is to vMotion vm after rescanning HBA on the destination host. That’s it!

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 metadata.zip), creating subfolder in the current directory (replacing if already exists), you need to run the following command:
Extract-ZipFile -ZipFilePath metadata.zip -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.

 

Restarting managements agents

You know the situation when the host stops reporting its performance counters, do you? CPU and RAM load are showing nils.. A simple two-liner to fix the issue at your disposal:

 

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!

$Env:Path
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.

Snippets
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

Help
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:

Passwords
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):

Certificate
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 http://timestamp.globalsign.com/scripts/timestamp.dll

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.

GitHub
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!

The power of Get-View

Today we’re going to discover very useful Get-View cmdlet. I’m sure most of you have seen it in many scripts found across the web. This cmdlet returns .NET view objects thus exposing API methods and properties to PowerShell environment. This is crucial in advanced manipulating with vSphere infrastructure.

First it’s worth mentioning that getting implementation objects (those produced by Get-VM, Get-VMHost, etc) takes more time than getting view objects, though in the last versions I found the gap decreased significantly. In fact impl objects are composed of the properties of corresponding view objects.

Let’s discover the available parameters that need to be discussed:

-VIObject, -Id
View object can be retrieved by MoRef (-Id) or by passing the impl object (-VIObject) to cmdlet. Don’t forget to use -Server parameter when retrieving objects by MoRef if you are working with multiple default vCenter servers since MoRef are not unique across different vCenter servers.

-Property
This parameter allows you to limit the object properties to be retrieved that can significantly speed up the query execution. Going ahead, one interesting thing you may wonder while using this parameter together with -Filter: does the property that objects are filtered by need to be specified here? The answer is no, they don’t.

-Filter
This parameter accepts the hash table:
@{Name='^TestVM[1-9]$'; 'Config.Version'='7'; 'Snapshot'=''}
where both keys and values represent the strings and imply that for any object returned every specified key must match the corresponding value. The key can be any nested property but not the property of linked object – for linked objects use -SearchRoot parameter (more on that later). You can use the power of regular expressions for value strings. You may wonder how to test whether the property exists for the object? Just specify this property with the empty value. The example above will filter all vms with name matching ‘TestVM’, hardware version equal to ‘vmx-07’ and for which at least one snapshot exists.
Filtering on the server side prevents the objects that don’t satisfy the specified criteria to be transfered to the client thus it again increases the performance.

-ViewType
Unfortunately cmdlet implementation is missing the list of possible values for this parameter (any reason this can’t be implemented?). You can find out accepted viewtypes by calling Get-View with any incorrect string. Having the list it’s easy to understand which type to use in a query. To learn more about types, inheritance and so on go to API reference guide.

Another really useful objects that can be retrieved by Get-View are different types of managers. The full list can be obtained with ‘(Get-View ServiceInstance).Content’ call.
One can use them to manipulate alarms (Get-View AlarmManager), tasks (Get-View TaskManager), files and so on. So it’s very useful stuff too.

Ok, this part is done. Now let’s explore the base view object.
We have an interesting liaison here: UpdateViewData method and LinkedView property.
Until UpdateViewData is invoked the LinkedView property is empty. Parameters of UpdateViewData invocation are the (multiple) properties of current or linked object you want to obtain. Together with the property name we can specify the property object type. In some cases it’s quite useful to restrict the possible values if the property is the list of object of different types. Let’s see an example because the code is better than thousand words. Consider navigating through inventory folders: every time you want to get the child objects but only those of type ‘Folder’:

The type restriction is neccessary when you specify the property path that include containers and this property doesn’t belong to all entities container can include. Thus
$FolderView.UpdateViewData('ChildEntity.ChildEntity')
won’t work because folder can include vm objects for which ChildEntity property isn’t defined.

Got it? Then another example of digging even deeper:

So, instead of calling Get-View multiple times leverage UpdateViewData method call. It really accelerates your scripts where you need to get nested view objects.

Now you are aware of the foundation of advanced PowerCLI scripting. Use Get-View in your scripts when processing the bulk of data and the speed is a vital factor.
When operating few objects stay with common impl-getting cmdlets not to loose the simplicity of your scripts.

There is another batch of interesting information I’m ready to share.
Stay tuned!

Fast Suspend/Resume

Have you ever come across the term in subj? It’s time to reveal what it stands for.
First, three examples when this action can be performed.
To enable CBT for virtual machine in addition to make vm reconfiguration one need to perform so called stun/unstun cycle for vm. This could be power on/off, suspend/resume, create/remove snapshot, vm migration.
Another example is changing the build type for running vm (release/debug/stats). This can be done in vm advanced settings tab or via command line utils. In order to BuildType change is applied FSR is performed transparently by the 5.x hypervisor (for ESXi 4.x vm is actually suspended and then resumed).
And the most frequent one is hot-add hardware to vm.
In fact Fast Suspend/Resume equals to migration to the same host – that’s simple.

Below you can find an example of CBT enabling script (most of backup tools enable it automatically).