PowerShell

Basic PowerShell Registry Value Helpers

Working with registry values in PowerShell can be a little cumbersome, so here are some example helpers that I am using to simplify some of my configuration scripts.

Function Get-RegistryValue {
    param (
        $key,
        $value
    )
 
    (Get-ItemProperty -Path $key -Name $value).$value
}
 
Function Test-RegistryValue {
    param (
        $key,
        $value
    )
 
    $data = Get-ItemProperty -Path $key -Name $value -ErrorAction SilentlyContinue
 
    if ($data) {
        $true
    }
    else {
        $false
    }
}
 
Function Set-RegistryValue {
    param (
        $key,
        $value,
        $data
    )
 
    Set-ItemProperty -Path $key -Name $value -Value $data
}
 
Function New-RegistryValue {
    param (
        $key,
        $value,
        $data = "",
        $propertyType = "String" #Default to string registy value types
    )
 
    New-ItemProperty -Path $key -Name $value -Value $data -PropertyType $propertyType | Out-Null
}
 
Function Remove-RegistryValue {
    param (
        $key,
        $value
    )
 
    Remove-ItemProperty -Path $key -Name $value | Out-Null
}
 
Function Rename-RegistryValue {
    param (
        $key,
        $value,
        $newValue
    )
 
    Rename-ItemProperty -Path $key -Name $value -NewName $newValue
}

Using PowerCLI to Uninstall vCenter Extensions

After finishing a CapacityIQ evaluation we wanted to uninstall the plug-in from vCenter. VMware KB article 1025360 shows how to do this, but it requires the Managed Object Browser. Per the security hardening guide we disabled the mob so this solution would not work as given. PowerCLI to the rescue.

Here are the steps given in the original article and how they translate into PowerCLI.

#1.In a web browser, navigate to http://<vcenter server name or IP>/mob.
#Where <vcenter server name or IP> is the name of your vCenter Server or its IP address.
Connect-VIServer vcenter001
 
#2.Click Content. 
#3.Click ExtensionManager. 
$em = Get-View ExtensionManager
 
#4.Select and copy the name of the plug-in you want to remove from the list of values under Properties. 
$em.ExtensionList | ft -Property Key
 
#5.Click UnregisterExtension. A new window appears. 
#6.Paste the name of the plug-in and click Invoke Method. This removes the plug-in.
$em.UnregisterExtension("extension key name")
 
#7.Close the window. 
#8.Refresh the Managed Object Type:ManagedObjectReference:ExtensionManager window to verify if the plug-in is removed successfully.
# Note that we need to refresh the data before listing the plugins
$em.UpdateViewData()
$em.ExtensionList | ft -Property Key
 
# Log out
Disconnect-VIServer

VMware PowerCLI 4.1.1 Cmdlets by Noun

Generated using this post.

Noun Verbs
AdvancedSetting Get,New,Remove,Set
AlarmAction Get,New,Remove
AlarmActionTrigger Get,New,Remove
AlarmDefinition Get,Set
Annotation Get,Set
CDDrive Get,New,Remove,Set
Cluster Get,Move,New,Remove,Set
CustomAttribute Get,New,Remove,Set
CustomField New,Remove,Set
Datacenter Get,Move,New,Remove,Set
Datastore Get,New,Remove,Set
DatastoreItem Copy
DrsRecommendation Apply,Get
DrsRule Get,New,Remove,Set
ErrorReport Get
EsxCli Get
EsxTop Get
FloppyDrive Get,New,Remove,Set
Folder Get,Move,New,Remove,Set
HAPrimaryVMHost Get
HardDisk Copy,Get,New,Remove,Set
Inventory Get,Move,Remove
IScsiHbaTarget Get,New,Remove,Set
Log Get
LogType Get
NetworkAdapter Get,New,Remove,Set
NicTeamingPolicy Get,Set
OSCustomizationNicMapping Get,New,Remove,Set
OSCustomizationSpec Get,New,Remove,Set
PassthroughDevice Add,Get,Remove
PowerCLIConfiguration Get,Set
PowerCLIVersion Get
ResourcePool Get,Move,New,Remove,Set
ScsiController Get,New,Set
ScsiLun Get,Set
ScsiLunPath Get,Set
Snapshot Get,New,Remove,Set
Stat Get
StatInterval Get,New,Remove,Set
StatType Get
Task Get,Stop,Wait
Template Get,Move,New,Remove,Set
Tools Dismount,Mount,Update,Wait
UsbDevice Get,Remove
VApp Export,Get,Import,New,Remove,Set,Start,Stop
VICredentialStoreItem Get,New,Remove
VIEvent Get
View Get
VIObjectByVIView Get
VIPermission Get,New,Remove,Set
VIPrivilege Get
VIProperty New,Remove
VIRole Get,New,Remove,Set
VirtualPortGroup Get,New,Remove,Set
VirtualSwitch Get,New,Remove,Set
VIServer Connect,Disconnect
VM Get,Move,New,Remove,Restart,Set,Start,Stop,Suspend
VMGuest Get,Restart,Shutdown,Suspend
VMGuestFile Copy
VMGuestNetworkInterface Get,Set
VMGuestRoute Get,New,Remove
VMHost Add,Get,Move,Remove,Restart,Set,Start,Stop,Suspend
VMHostAccount Get,New,Remove,Set
VMHostAdvancedConfiguration Get,Set
VMHostAvailableTimeZone Get
VMHostDiagnosticPartition Get,Set
VMHostDisk Get
VMHostDiskPartition Format,Get
VMHostFirewallDefaultPolicy Get,Set
VMHostFirewallException Get,Set
VMHostFirmware Get,Set
VMHostHba Get,Set
VMHostModule Get,Set
VMHostNetwork Get,Set
VMHostNetworkAdapter Get,New,Remove,Set
VmHostNtpServer Add,Get,Remove
VMHostPatch Get,Install
VMHostProfile Apply,Export,Get,Import,New,Remove,Set
VMHostProfileCompliance Test
VMHostRoute Get,New,Remove,Set
VMHostService Get,Restart,Set,Start,Stop
VMHostSnmp Get,Set,Test
VMHostStartPolicy Get,Set
VMHostStorage Get,Set
VMHostSysLogServer Get,Set
VMQuestion Get,Set
VMResourceConfiguration Get,Set
VMScript Invoke
VMStartPolicy Get,Set

VMware PowerCLI 4.1 Cmdlets Summarized by Noun

Here is the list of VMware PowerCLI cmdlets ordered by noun. I find this easier to use when I am trying to write scripts. You can locate what items you want to work with and then see the action you can take. This post contains the code used to generate the list.

Noun Verbs
Annotation Get,Set
CDDrive Get,New,Remove,Set
Cluster Get,Move,New,Remove,Set
CustomAttribute Get,New,Remove,Set
CustomField New,Remove,Set
Datacenter Get,Move,New,Remove,Set
Datastore Get,New,Remove,Set
DatastoreItem Copy
DrsRecommendation Apply,Get
DrsRule Get,New,Remove,Set
ErrorReport Get
FloppyDrive Get,New,Remove,Set
Folder Get,Move,New,Remove,Set
HardDisk Copy,Get,New,Remove,Set
Inventory Get,Move,Remove
IScsiHbaTarget Get,New,Remove,Set
Log Get
LogType Get
NetworkAdapter Get,New,Remove,Set
NicTeamingPolicy Get,Set
OSCustomizationNicMapping Get,New,Remove,Set
OSCustomizationSpec Get,New,Remove,Set
PassthroughDevice Add,Get,Remove
PowerCLIConfiguration Get,Set
PowerCLIVersion Get
ResourcePool Get,Move,New,Remove,Set
ScsiLun Get,Set
ScsiLunPath Get,Set
Snapshot Get,New,Remove,Set
Stat Get
StatInterval Get,New,Remove,Set
StatType Get
Task Get,Stop,Wait
Template Get,Move,New,Remove,Set
Tools Dismount,Mount,Update
UsbDevice Get,Remove
VApp Export,Get,Import,New,Remove,Set,Start,Stop
VICredentialStoreItem Get,New,Remove
VIEvent Get
View Get
VIObjectByVIView Get
VIPermission Get,New,Remove,Set
VIPrivilege Get
VIProperty New,Remove
VIRole Get,New,Remove,Set
VirtualPortGroup Get,New,Remove,Set
VirtualSwitch Get,New,Remove,Set
VIServer Connect,Disconnect
VM Get,Move,New,Remove,Restart,Set,Start,Stop,Suspend
VMGuest Get,Restart,Shutdown,Suspend
VMGuestFile Copy
VMGuestNetworkInterface Get,Set
VMGuestRoute Get,New,Remove,Set
VMHost Add,Get,Move,Remove,Restart,Set,Start,Stop,Suspend
VMHostAccount Get,New,Remove,Set
VMHostAdvancedConfiguration Get,Set
VMHostAvailableTimeZone Get
VMHostDiagnosticPartition Get,Set
VMHostFirewallDefaultPolicy Get,Set
VMHostFirewallException Get,Set
VMHostFirmware Get,Set
VMHostHba Get,Set
VMHostModule Get,Set
VMHostNetwork Get,Set
VMHostNetworkAdapter Get,New,Remove,Set
VmHostNtpServer Add,Get,Remove
VMHostPatch Get,Install
VMHostProfile Apply,Export,Get,Import,New,Remove,Set
VMHostProfileCompliance Test
VMHostRoute Get,New,Remove,Set
VMHostService Get,Restart,Set,Start,Stop
VMHostSnmp Get,Set,Test
VMHostStartPolicy Get,Set
VMHostStorage Get,Set
VMHostSysLogServer Get,Set
VMQuestion Get,Set
VMResourceConfiguration Get,Set
VMScript Invoke
VMStartPolicy Get,Set

Quick and dirty PowerPath/VE output parser

Here is a quick and dirty PowerShell script to parse the output of the rpowermt command used to manage PowerPath/VE on ESX (for EMC arrays). I wrote the code quickly to solve a particular problem, but if I get requests I could extend it to parse the rest of the output and do so in a little more robust fashion.

Why do this? I am in the middle of migrations between frames and I needed an easy way to determine what needed moved when the storage admin said move all LUNs from CLARiiON XXXX to the new LUNs on YYYY – and make sure to move LUN 41 to LUN 88.

By parsing the output of rpowermt I could more easily determine the ID of the LUNs they indicated and map that to the extent properties of my datastores to determine what needed to move.

Two step usage:

  1. rpowermt host=esx001 display dev=all > esx001_lundata.txt
  2. $lunInfo = .\SimplePowerVeParse esx001_lundata.txt

Alternate ways of accomplishing the same thing:

  1. The Storage Viewer plugin from EMC would be helpful in determining this from the GUI, but due to political reasons this is not yet deployed in production.
  2. I originally wanted to try and talk to the CIM provider for PowerPath, but quickly found that the Get-WSManInstance cmdlet’s authentication assumptions were very Windows centric.

The script (more…)

VMware PowerShell Get-VIHumanReadablePath

An example of how to get the human readable path of an object in the VMware SDK. This is using PowerShell and requires that PowerCLI be installed, but should be easily converted to other languages.

Function Get-VIHumanReadablePath
{
    param
    (
        $target
    )
 
    try
    {
        if ($target.GetType().BaseType -ne [VMware.Vim.ManagedEntity])
        {
            $target = $target | Get-View -ErrorAction SilentlyContinue
        }
    }
    catch
    {
        $target = $null
    }
 
    if (!$target)
    {
        throw "Get-VIHumanReadablePath: Could not get the Managed Entity representation of -target"
    }
 
    $path = $target.Name
    while ($target.Parent)
    {
        $target = Get-View $target.Parent  
        $path = $target.Name + "/" + $path           
    }
 
    $path
}

Example usage

Get-VIHumanReadablePath (Get-Folder Linux)
Get-VIHumanReadablePath (Get-VM LinuxTemp01)
Get-VIHumanReadablePath (Get-VM LinuxTemp01 | Get-View)
Get-VIHumanReadablePath (Get-ResourcePool Prod)
Get-VIHumanReadablePath (Get-VM LinuxTemp01 | Get-ResourcePool)
Get-VIHumanReadablePath (Get-VMHost esx001.local)

Another Orchestrator/PowerShell hang issue

It has come to my attention that some times the scripts will still hang after using the trick from a previous post to fix an issue with standard input when running PowerShell in Orchestrator workflows. After further research there appears to be an issue with stderr hanging the scripts in a similar way to stdin. To be safe you should do something with the output from stderr (where error messages are sent).

You can do at least three things

//Throw it away with 2>NUL
command = new Command("cmd.exe /c powershell.exe -File c:\\orchestrator\\test.ps1 < NUL 2>NUL");
 
//Log it to a new file with 2> filename
command = new Command("cmd.exe /c powershell.exe -File c:\\orchestrator\\test.ps1 < NUL 2>c:\\orchestrator\\stderr.log");
 
//Send it wherever standard output goes using 2>&1
command = new Command("cmd.exe /c powershell.exe -File c:\\orchestrator\\estest.ps1 < NUL 2>&1");

For further reading on the topic of standard input, output, and error please see
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx?mfr=true

Running PowerShell in VMware Orchestrator – updated

Updated 7/29/2010 – I have added a new follow up post this post regarding another related hanging issue. Please make sure to check it out.

This is a copy of my comment in the VMware Communities, but some times the Google search results for items in this blog show up and the ones for the communities do not.

The original problem is that PowerShell scripts hang when running them in Orchestrator.

I have spent some time on this and have a way to make it work. For some reason when run this way the $input variable in Powershell is expecting a pipeline and I believe it just waits for pipelined input.

The $input variable is of type System.Management.Automation.Runspaces.Pipeline instead of the standard System.Collections.ArrayList+ArrayListEnumeratorSimple when running scripts. I have tried using the methods in the Pipeline class to clear things up to no avail. I have also tried using the input property on the Orchestrator Command class, but I could not get it to work. I am just getting started with Orchestrator though, so it may be my lack of knowledge.

As a workaround you can input NUL to the script or command using cmd.exe.

// Run a command
command = new Command("cmd /c powershell.exe -Command dir variable: >> c:\\orchestrator\\input.out < NUL");
command.execute(true);
 
//Run a script
command = new Command("cmd /c powershell.exe -File c:\\orchestrator\\input.ps1 < NUL");
command.execute(true);

Adding VMware PowerCLI to your standard PowerShell environment

In order to get access to PowerCLI when using another PowerShell shortcut or environment you can run the following commands which is what happens when you run the VMware provided shortcut.

# Adds the base cmdlets
Add-PSSnapin VMware.VimAutomation.Core
# Add the following if you want to do things with Update Manager
Add-PSSnapin VMware.VumAutomation
# This script adds some helper functions and sets the appearance. You can pick and choose parts of this file for a fully custom appearance.
. "C:\Program Files\VMware\Infrastructure\vSphere PowerCLI\Scripts\Initialize-VIToolkitEnvironment.ps1"

**UPDATE 2/7/2013**
As Paul noted in the comments, the new initialization script is called Initialize-PowerCLIEnvironment.ps1. Also, if you are on a 64 bit system the files will be in “Program Files (x86)”

Note on the last line that there is a space between the “.” and the path to the script. That space is very important as it means we are including or “dot sourcing” the file.

If you want this all to load every time you launch PowerShell you can add these commands to your profile startup scripts. This is a great place to add functions or aliases that you use all the time. The profile is run once when the PowerShell environment is launched.