Archive for March 2013

Given a sample script, modify the script to perform a given action

LogIcon

Basic Script 1

This script will connect to the vCenter Server and get all VMs in a folder followed by starting those VMs in a folder

$vms = get-vm -Location Test-Folder
# Start each vm in the folder
ForEach($vm in $vms)
{
start-vm -RunAsync -VM $vm -Confirm:$false
}

Basic Script 2

This script will go and find any VMs which have their CD Drive connected

Get-VM | Where-Object {$_ | Get-CDDrive |  Where-Object { $_.ConnectionState.Connected -eq “true”  } } |  Select-Object Name

Advanced Reporting Script

This script should only show RDMs but for both compatibility modes

http://communities.vmware.com/message/1063909

$RDMs = @()
foreach($vm in (Get-View -ViewType “VirtualMachine”)) {
    foreach($dev in ($vm.Config.Hardware.Device | where {($_.gettype()).Name -eq “VirtualDisk”})) {
        if(($dev.Backing.CompatibilityMode -eq “physicalMode”) -or ($dev.Backing.CompatibilityMode -eq “virtualMode”)) {
            $objRdm = “” | select VMName, VMDK, UUID, DiskLabel, SCSIBus, SCSIDevice, Mode
            $objRdm.VMName = $vm.Name
            $objRdm.VMDK = $dev.Backing.FileName
            $objRdm.UUID = $dev.Backing.LunUuid
            $objRdm.DiskLabel = $dev.DeviceInfo.Label
            $objRdm.SCSIBus = ( $vm.Config.Hardware.Device | ? { $_.Key -eq $dev.ControllerKey }).BusNumber
            $objRdm.SCSIDevice = $dev.UnitNumber
            $objRdm.Mode = $dev.Backing.CompatibilityMode
            $RDMs += $objRdm
        }
    }
}

$report = @()

foreach ($cluster in (Get-View -ViewType “ClusterComputeResource”)) {
    $vmhostsview = $cluster.host | % { Get-View $_ }
    $vmhostview = $vmhostsview | Select -first 1
    $ScsiLuns = $vmhostsview | % { $_.Config.StorageDevice.ScsiLun } | Select -unique *
    $UUIDs = $ScsiLuns | Select -unique UUID
    $Datastores = $vmhostsview | % { $_.Config.FileSystemVolume.MountInfo } | % { $_.Volume } | Select -Unique *
    $HostLUN = $vmhostsview | % { $_.Config.StorageDevice.ScsiTopology.Adapter } | % { $_.Target | % { $_.LUN } } | Select -unique *
    foreach ($UUID in $UUIDs) {
        $Lun = $ScsiLuns | ? { $_.UUID -eq $UUID.UUID } | Select -first 1
        $objVolume = “” | Select Cluster, VolumeName, CanonicalName, DisplayName, VolumeType, CapacityGB, BlockSizeMb, VMFSVersion, LunType, Vendor, Model, HostLUN, VM, VMDiskLabel, VMSCSIBus, VMSCSIDevice, Revision, ScsiLevel, UUID
        $objVolume.Cluster = $cluster.Name
        $objVolume.CanonicalName = $Lun.CanonicalName
        $objVolume.HostLUN = ($HostLUN | ? { $_.ScsiLun -eq $Lun.Key } | select -unique LUN).LUN
        $objVolume.UUID = $Lun.Uuid
        $objVolume.CapacityGB = $Lun.Capacity.Block * $Lun.Capacity.BlockSize / 1GB
        $objVolume.DisplayName = $Lun.DisplayName
        $objVolume.LunType = $Lun.LunType
        $objVolume.Vendor = $Lun.Vendor
        $objVolume.Model = $Lun.Model
        $objVolume.Revision = $Lun.Revision
        $objVolume.ScsiLevel = $Lun.ScsiLevel
        foreach ($vol in $Datastores) {
            if ($vol.extent | % { $_.diskname -eq $Lun.CanonicalName}) {
                $objVolume.VolumeName = $vol.Name
                $objVolume.BlockSizeMb = $vol.BlockSizeMb
                $objVolume.VMFSVersion = $vol.Version
                $objVolume.VolumeType = “vmfs”
            }
        }
        foreach ($rdm in $RDMs) {
            if ($Lun.Uuid -eq $rdm.UUID) {
                $objVolume.VolumeName = $rdm.VMDK
                $objVolume.VM = $rdm.VMName
                $objVolume.VMDiskLabel = $rdm.DiskLabel
                $objVolume.VMSCSIBus = $rdm.SCSIBus
                $objVolume.VMSCSIDevice = $rdm.SCSIDevice
                if ($rdm.Mode -eq “virtualMode” ) { $objVolume.VolumeType = “rdm” }
                if ($rdm.Mode -eq “physicalMode”) { $objVolume.VolumeType = “rdmp” }
            }
        }
        $report += $objVolume
    }
}
$report | Export-Csv “C:\report.csv” -NoTypeInformation -UseCulture

Running PowerShell Scripts

  • Launch PowerShell
  • Make sure Set-ExecutionPolicy RemoteSigned is the policy
  • Run the script by entering the full path to the script (c:\scripts\myscript.ps1), or if it’s in the current directory, prefix it with a period followed by a backslash (.\myscript.ps1).

Identify environment variables usage

index

PowerShell providers

A PowerShell provider, or PSProvider, is an adapter. It’s designed to take some kind of data storage and make it look like a disk drive. PowerShell Providers are .NET programs that allow us to work with data stores as if they were mounted drives. This simplifies accessing external data outside the PowerShell environment. For example, we can access the registry as if it were a file system. You can see a list of installed providers right within the shell:

  • get-psprovider

env1

Notice that each provider has different capabilities. This is important, because it
affects the ways in which you can use each provider. These are some of the common
capabilities you’ll see:

  • ShouldProcess—Means the provider supports the use of the -WhatIf and -Confirm parameters, enabling you to “test” certain actions before committing to them.
  • Filter—Means the provider supports the -Filter parameter on the cmdlets that manipulate providers’ content.
  • Credentials—Means the provider permits you to specify alternate credentials when connecting to data stores. There’s a -credential parameter for this.
  • Transactions—Means the provider supports the use of transactions, which allows you to use the provider to make several changes, and then either roll back or commit those changes as a single unit.

PowerShell Drives “PSDrive”

We connect to PowerShell Providers by mounting the Providers PowerShell Drive(PSDrive). Most Providers have only one PSDrive, the exceptions are the FileSystem Provider(depends on the number of drives on the system) and the Registry Provider(HKLM and HKCU).

You use a provider to create a PSDrive. A PSDrive uses a single provider to connect to some actual data storage. You’re essentially creating a drive mapping, much like you might have in Windows Explorer, but a PSDrive, thanks to the providers, is able to connect to much more than disks. Run the following command to see a list of currently connected drives:

  • get-psdrive

env2

You can change to these drives by typing the below. Windows environment variables are visible as a PS drive called Env:

  • set-location -path env:
  • Try typing dir
  • You can also type it all in one as get-child-item env: or dir env:

envvariable

The PowerShell Environment Provider

The Environment Providers are equivalent to running the “set” command in a windows CMD command shell. It provides a listing of all the environment variable defined on the system. Graphically, you can view the environment variables by going to System Properties > Advanced Tab > Click the “Environment Variables” button

shell

Use Datastore and Inventory Providers

index

The Inventory Provider

The Inventory Provider (VimInventory ) is designed to expose a raw inventory view of the inventory items from a server. It enables interactive navigation and file-style management of the VMware vSphere inventory.
By creating a PowerShell drive based on a managed object (such as a datacenter), you obtain a view of its contents and the relationships between the items. In addition, you are able to manipulate objects (move, rename or delete them) by running commands from the vSphere PowerCLI console.

When you connect to a server with Connect-VIServer, the cmdlet builds two default inventory drives: vi and vis

  • The vi inventory drive shows the inventory on the last connected server.
  • The vis drive contains the inventory all vSphere servers connected with in the current vSphere PowerCLI session.

You can use the default inventory drives or create custom drives based on the default ones

psdrive

To view the content of a default inventory drive

  • Access the vi inventory drive by typing cd vi:
  • Type dir

vi

The Datastore Provider

The Datastore Provider (VimDatastore) is designed to provide access to the contents of one or more datastores. The items in a datastore are files that co ntain configuration, virtua l disk, and the other data associated with a virtua l machine.All file operations are case-sensitive.

When you connect to a server with Connect-VIServer , the cmdlet builds two default datastore drives:

  • vmstore: The vmstore drive displays the datastores available on the last connected vSphere server.
  • vmstores:  The vmstores drive contains all datastores available on all vSphere servers connected within the current vSphere PowerCLI session. You can use the default inventory drives or create custom drives based on the default ones

To browse a default datastore drive

  • Access the vmstore drive – set-location vmstores: or type cd vmstore:
  • List the drive content:dir
  • Follow the commands down

Capture