Upload
truongnhi
View
255
Download
3
Embed Size (px)
Citation preview
E-Guide
Expert Insight into PowerShell’s
Scripting
PowerShell offers new users the ability to quickly learn how to carry
out common administration tasks with the basic PowerShell cmdlets.
In this e-guide from SearchWindowsServer.com, discover the
numerous benefits of implementing Microsoft PowerShell. Learn about
the several ways to manage Hyper-V with PowerShell. Plus discover
different approaches in scripting and aspects of virtualization
management.
Sponsored By:
SearchWindowsServer.com E-Guide
Expert Insight into PowerShell’s Scripting
Sponsored By: Page 2 of 13
E-Guide
Expert Insight into PowerShell’s
Scripting
Table of Contents
Scripting: VMware PowerCLI vs. Microsoft PowerShell
Using PowerShell to manage Microsoft Hyper-V
Resources from Dell Compellent
SearchWindowsServer.com E-Guide
Expert Insight into PowerShell’s Scripting
Sponsored By: Page 3 of 13
Scripting: VMware PowerCLI vs. Microsoft PowerShell
By Mike Laverick, Contributor
It may seem unlikely to compare VMware PowerCLI and Microsoft PowerShell, because the
former requires the latter to be installed first and is merely a vendor-specific addition to the
core PowerShell environment.
It's also unlikely that someone would pick a virtualization platform merely based on its
scripting capabilities. So rather than setting up a grudge match pitting one company against
another, I will tell you what I like and dislike about each implementation. Hopefully, I can
explain how both companies can improve their respective scripting offerings. Let's start with
Microsoft.
Microsoft PowerShell
One aspect of virtualization management I like about Microsoft SCVMM is its built-in View
Script window. This acts like a script recorder that gives you the ability to capture
administrative actions as PowerShell scripts. A good example of this is when you are
carrying out a migration task within SCVMM in order to move a VM to another Hyper-V host.
At the end of the wizard a "View Script" button will display, showing the exact PowerShell
commands needed in a script.
Figure 1
SearchWindowsServer.com E-Guide
Expert Insight into PowerShell’s Scripting
Sponsored By: Page 4 of 13
In part, this is simply a happy fortune that comes from the way SCVMM was developed.
Initially, SCVMM was designed to be managed by PowerShell, and then later a graphic
management shell was developed around it so Windows admins didn't need to learn the
PowerShell behind it.
It isn't difficult for Microsoft to expose the underlying PowerShell executing in the
background. This won't help admins write PowerShell scripts with variables for each loop,
error checking and logging, but it is very useful to folks who are new to PowerShell and at
least gets them over the hump of learning how to carry out common administration tasks
with the basic PowerShell cmdlets.
Today, Hyper-V doesn't have an official set of cmdlets, but a set was built by James O'Neill
and is stored on Codeplex website. O'Neill took the APIs and wrote his cmdlets based on
this. With the release of SCVMM 2012, the number of cmdlets is going to increase
significantly, as the amount of tasks one can do in SCVMM in general is increasing
substantially.
VMwarePowerCLI
VMware has made great strides with a number of new features to PowerShell, which it calls
PowerCLI. In successive releases the company has significantly upped the number of
cmdlets in the product to nearly 250. Earlier additions lacked cmdlets to control the ESX
host iSCSI stack although the recent vSphere4.1 release has plugged that gap.
There are still the odd holes here and there. For instance, there aren't any meaningful
cmdlets around VMware's Distributed vSwitches. Although its fair to say that PowerCLI 4.1
did update cmdlets which allow the administrator report information about an existing
DvSwitch configuration including enhancements to the following cmdlets:
Get-VirtualSwitch
Get-VMHost
Get-VM
Get-VMHostNetworkAdapter
New-NetworkAdapter, Set-NetworkAdapter
SearchWindowsServer.com E-Guide
Expert Insight into PowerShell’s Scripting
Sponsored By: Page 5 of 13
It appears the company favors its "Host Profiles" feature as the main configuration tool for
newly created ESX hosts. Customers who buy the Enterprise and SKU qualify for both
Distributed vSwitches and Host Profiles.
There are new deployment methods coming in future releases which emphasize the use of
host profiles over PowerCLI for deployment of new ESX hosts. It's worth mentioning that
vExpert Luc Dekens has developed his own functions that allow for management of
DvSwitches. With that said, the primary use of PowerCLI in the VMware Community is
reporting and checking the vSphere environment. Scripts such as virtu-al.net "Health
Check" also have been extremely popular.
For everything else there is the VMware SDK. This extremely rich interface allows access to
practically every action one may want to carry out, both at the host and the vCenter
management server. This is in contrast to Microsoft where the only officially supported
cmdlets are to SCVMM. There is some similarity between VMware and Microsoft there: both
offer very limited PowerShell support for the so-called "free" editions of their hypervisors.
Both companies are wary that customers could get a hypervisor for free, and manage it with
command-line tools rather than paying a premium for the management piece.
The vCenter itself lacks the integration of PowerCLI directly in the vSphere Client. In
searching for some way of "recording" administration as PowerCLI code, one could look at
VMware Onyx, which is a free appliance that sits between the vSphere Client and vCenter
and outputs the actions as raw PowerCLI SDK code. As a side note, it also outputs actions in
a JavaScript format suitable for VMware's Orchestrator, a technology sadly underused by
most VMware admins.
The output from Onyx a might be a bit overwhelming but don' be intimidated. There are
more friendly ways of carrying out administration tasks via a GUI, as well as collecting the
PowerCLI code after the task is completed. One should play around with the PowerGUI front
end and its various PowerPacks that extend its functionality. PowerGUI works with a vast
array of administration tasks including Active Directory, but from a virtualization perspective
there are PowerPacks for VMware vSphere, Citrix XenServer, Microsoft HyperV, Virtual Disk
Analysis, HP Virtual Connect and Quest vWorkspace.
SearchWindowsServer.com E-Guide
Expert Insight into PowerShell’s Scripting
Sponsored By: Page 6 of 13
Figure 2
In the meantime, VMware is attempting to extend PowerCLI support to its other
technologies, which is something that Microsoft is already down the road on. There is a
PowerCLI for VMware virtual desktop solution, called View, but the implementation is very
different from that of vSphere PowerCLI. It has a feeling more akin to a DOS command-line
system than PowerShell and allows for pipelining and querying objects for their properties
and attributes. As of now technologies like VMware Site Recovery Manager do not have
PowerCLI, but it is likely on VMware's radar screen.
For the benefit of those folks not living in the Windows world, PowerShell and PowerCLI
have sent shockwaves through the system administration world. But there are Linux-based
scripters who may feel left out in the cold. VMware offers Perl and Microsoft does not, but
that is to be expected.
SearchWindowsServer.com E-Guide
Expert Insight into PowerShell’s Scripting
Sponsored By: Page 7 of 13
These other toolkits aren't gaining much traction in the communities I travel in. Similar
older CLI and remote CLI seem to be withering too such as VMware's port of its "ESX"
commands to the vCLI and vCLI appliance. Right now they feel like an intermediary step
intended to wean VMware customers off their dependency on the old "Service Console"
environment. Right now it feels like PowerShell and PowerCLI will rule the sysadmin's roost
for the foreseeable future.
SearchWindowsServer.com E-Guide
Expert Insight into PowerShell’s Scripting
Sponsored By: Page 8 of 13
Using PowerShell to manage Microsoft Hyper-V
By Brandon Shell, Contributor
Many admins use PowerShell to automate components like user creation and folder
permissions, but virtualization technologies can also be managed from the command line,
including Microsoft Hyper-V.
While there are several ways to manage Hyper-V with PowerShell, this article will focus on
the free approaches using Windows Management Instrumentation (WMI) scripting and an
open source tool from CodePlex.
Before using WMI scripting to manage Hyper-V, it’s important to understand what classes
are available. Microsoft’s list includes a significant number of classes and while is fairly
complete, they are not necessarily easy to use and are certainly not intuitive. Therefore,
using WMI to manage Hyper-V is not for the faint of heart.
One of the more popular methods for managing Hyper-V with PowerShell is with PowerShell
Management Library for Hyper-V (PSHyperV) a free, open source CodePlex project written
by James O’Neil. This is by far the best free option out there and gives administrators a very
thorough collection of cmdlets that do everything from virtual machine inventory to virtual
network management. Let’s touch on a few of them:
Get-VM -- returns all the virtual machines on a given Hyper-V server (see Figure 1).
Figure 1: Get-VM command
SearchWindowsServer.com E-Guide
Expert Insight into PowerShell’s Scripting
Sponsored By: Page 9 of 13
The following code demonstrates the Get-VM command:
Function Get-VM {# .ExternalHelp MAML-VM.XML param( [parameter(ValueFromPipeLine = $true)] [ValidateNotNullOrEmpty()][Alias("VMName")] $Name = "%",
[parameter()][ValidateNotNullOrEmpty()] $Server = ".", #May need to look for VM(s) on Multiple servers [Switch]$Suspended, [switch]$Running, [switch]$Stopped ) Process { # In case people are used to the * as a wildcard... if ($Name.count -gt 1 ) {[Void]$PSBoundParameters.Remove("Name") ; $Name | ForEach-object {Get-VM -Name $_ @PSBoundParameters}} if ($name -is [String]) { $Name = $Name.Replace("*","%") # Note in V1 the test was for caption like "Virtual%" which did not work in languages other than English. # Thanks to Ronald Beekelaar - we now test for a processID , the host has a null process ID, stopped VMs have an ID of 0.
$WQL = "SELECT * FROM MSVM_ComputerSystem WHERE ElementName LIKE '$Name' AND ProcessID >= 0" if ($Running -or $Stopped -or $Suspended) { $state = "" if ($Running) {$State += " or enabledState = " + [int][VMState]::Running } if ($Stopped) {$State += " or enabledState = " + [int][VMState]::Stopped } if ($Suspended) {$State += " or enabledState = " + [int][VMState]::Suspended } $state = $state.substring(4) $WQL += " AND ($state)" } Get-WmiObject -computername $Server -NameSpace $HyperVNamespace -
Query $WQL | Add-Member -MemberType ALIASPROPERTY -Name "VMElementName" -
Value "ElementName" -PassThru
} elseif ($name.__class) { Switch ($name.__class) { "Msvm_ComputerSystem" {$Name} "Msvm_VirtualSystemSettingData" {get-wmiobject - computername $Name.__SERVER -namespace $HyperVNamespace -Query "associators of {$($name.__path)} where resultclass=Msvm_ComputerSystem"} Default get-wmiobject -
SearchWindowsServer.com E-Guide
Expert Insight into PowerShell’s Scripting
Sponsored By: Page 10 of 13
computername $Name.__SERVER -namespace $HyperVNamespace -Query "associators of {$($Name.__path)} where resultclass=Msvm_VirtualSystemSettingData" | ForEach-Object {$_.getRelated("Msvm_ComputerSystem")} | Select-object -unique } } } } }
As you can see, the code basically wraps the WMI class with some helper logic and reports
the results.
Get-VMSwitch -- Returns all the virtual switches on the Hyper-V server (see Figure 2).
Figure 2: Get-VMSwitch command
The following code demonstrates the Get-VMSwitch command:
Function Get-VMSwitch {# .ExternalHelp MAML-VMNetwork.XML param( [parameter(ValueFromPipeline = $true)][Alias("Name")] [String]$VirtualSwitchName="%",
[parameter()][ValidateNotNullOrEmpty()] $Server = "." #Can query multiple servers for switches ) process { $VirtualSwitchName=$VirtualSwitchName.replace("*","%") Get-WmiObject -computerName $server -NameSpace $HyperVNamespace -query "Select * From MsVM_VirtualSwitch Where elementname like
'$VirtualSwitchname' " } }
SearchWindowsServer.com E-Guide
Expert Insight into PowerShell’s Scripting
Sponsored By: Page 11 of 13
Get-VMSnapShot -- Provides all the snapshots on the Hyper-V server (see Figure 3).
Figure 3: Get-VMSnapShot command
The following command demonstrates the Get-VMSnapShot command:
Function Get-VMSnapshot {# .ExternalHelp MAML-VMSnapshot.XML Param( [parameter(Position=0 , ValueFromPipeline = $true)] $VM = "%",
[String]$Name="%",
[parameter()][ValidateNotNullOrEmpty()] $Server="." , [Switch]$Current, [Switch]$Newest, [Switch]$Root ) process{ if ($VM -is [String]) {$VM=(Get-VM -Name $VM -Server $server) } if ($VM.count -gt 1 ) {[Void]$PSBoundParameters.Remove("VM") ; $VM
|
ForEach-object { Get-VMSnapshot -VM $_ @PSBoundParameters}} if ($vm.__CLASS -eq 'Msvm_ComputerSystem') { if ($current) {Get-wmiobject -computerNam $vm.__server - Namespace $HyperVNamespace -q "associators of {$($vm.path)} where
assocClass=MSvm_PreviousSettingData"} else {$Snaps=Get-WmiObject -computerName $vm.__server -NameSpace
$HyperVNameSpace -Query "Select * From MsVM_VirtualSystemSettingData Where
systemName='$($VM.name)' and instanceID <> 'Microsoft:$($VM.name)' and elementName like '$name' " if ($newest) {$Snaps | sort-object -property creationTime | select-object -last 1 } elseif ($root) {$snaps | where-object {$_.parent -eq $null} } else {$snaps} }
SearchWindowsServer.com E-Guide
Expert Insight into PowerShell’s Scripting
Sponsored By: Page 12 of 13
} } }
PSHyperV includes several additional functions to help admins perform related tasks,
including finding, manipulating and configuring different components of the hypervisor and
can be found on the CodePlex website.
Writing WMI wrappers and using PSHyperV are just a few of the ways admins can manage
Hyper-V using PowerShell. Note that the latest release of PSHyperV isn’t a complete
version, and thus, isn’t as stable as other options may be.
SearchWindowsServer.com E-Guide
Expert Insight into PowerShell’s Scripting
Sponsored By: Page 13 of 13
Resources from Dell Compellent
Dell Compellent and Microsoft Integration: Automating and Creating Efficiency for
the Data Center
Self-Service Provisioning and the Private Cloud
The Right Team to Power Efficiency
About Dell Compellent
Compellent Technologies (NYSE: CML) has created a revolutionary enterprise storage
solution that automates the movement and management of data at a more granular level.
We call it Fluid Data, and it’s the future of data storage. This patented, built-in storage
intelligence delivers significant efficiency, scalability and flexibility. Only a Fluid Data
architecture can actively, intelligently manage your data to cut cost, time, and risk for your
business. With an all-channel sales network in 35 countries, Compellent is one of the fastest
growing enterprise storage companies in the world.