Chapter8AutomationUsingPowerShellVirtualMachineManagerisoneoftherstMicrosoftsoftwareproductstofullyadoptWindowsPowerShellandofferitsusersacompletemanagementinterfacetailoredforscript-ing.
FromtherstreleaseofVMM2007,theVirtualMachineManagerAdministratorConsolewaswrittenontopofWindowsPowerShell,utilizingthemanycmdletsthatVMMoffers.
ThisapproachmadeVMMveryextensibleandpartnerfriendlyandallowscustomerstoaccomplishanythingthatVMMoffersintheAdministratorConsoleviascriptsandautomation.
WindowsPowerShellisalsotheonlypublicapplicationprogramminginterface(API)thatVMMoffers,givingbothdevelopersandadministratorsasinglepointofreferenceformanagingVMM.
WritingscriptsthatinterfacewithVMM,Hyper-V,orVirtualServercanbemadeveryeasyusingWindowsPowerShell'ssupportforWMI,.
NET,andCOM.
Inthischapter,youwilllearnto:DescribethemainbenetsthatPowerShelloffersforVMMUsetheVMMPowerShellcmdletsCreatescheduledPowerShellscriptsVMMandWindowsPowerShellSystemCenterVirtualMachineManager(VMM)2007,therstreleaseofVMM,wasoneoftherstproductstodevelopitsentiregraphicaluserinterface(theVMMAdministratorCon-sole)ontopofWindowsPowerShell(previouslyknownasMonad).
ThisapproachprovedveryadvantageousforcustomersthatwantedalloftheVMMfunctionalitytobeavailablethroughsomeformofanAPI.
TheVMMteammadeearlybetsonWindowsPowerShellasitspublicmanagementinterface,andtheyhavenotbeendisappointedwiththeresults.
Withitsconsis-tentgrammar,thegreatintegrationwith.
NET,andtheabundanceofcmdlets,PowerShellisquicklybecomingthemanagementinterfaceofchoiceforenterpriseapplications.
UnlikeothertraditionalpublicAPIsthatfocusondevelopers,VMM'sPowerShellinterfaceisdesignedfortheadministrator.
Withtheextensivehelpcontentsandthewell-documentedSystemCenterVirtualMachineManagerScriptingGuidethatisavailablefromtheMicrosoftDownloadCenter,theVMMteampositioneditscmdletstobethepremierwayofscriptinginyourvirtualizationenvironment.
InadditiontotheVMMcmdlets,yourscriptscanbeenhancedbythebuilt-insupportthatWindowsPowerShellhasforavarietyofdatastores,likethelesystem,theRegistry,andWMI.
328CHAPTER8AUTOMATIONUSINGPOWERSHELLInstallingtheVMMPowerShellCmdletsEventhoughtheVMMPowerShellinterfacedoesnothaveitsowninstaller,itisalwaysinstalledaspartoftheVMMAdministratorConsolesetup.
VMMSetupwillinstallthe32-bitversionoftheAdministratorConsoleon32-bitsystemsandthe64-bitversionoftheAdministratorConsoleon64-bitsystems.
DuetothenatureoftheVMMcmdlets,someutilizebothnativeand.
NETbinariesintheirimplementation.
ThisapproachprohibitstheVMMPowerShellcmdletsfrombeingarchitectureindependent,whichmeansthatonly32-bitPowerShellcmdletswillworkona32-bitsystem.
The64-bitPowerShellcmdletshavethesameissueandwillworkononlya64-bitsystem.
AnyprocessthatattemptstoloadthePowerShellrunspaceandinvoketheVMMcmdletsneedstobeawareofthisrestrictionandfactorthislimitationinthedesign.
VMM2008iscertiedtoworkwithbothWindowsPowerShellversion1.
0andversion2.
0.
WindowsPowerShellisalreadyincludedaspartofWindowsServer2008andWindowsServer2008R2,anditcanbedownloadedforfreefromtheMicrosoftwebsiteatthefollowinglocation:http://www.
microsoft.
com/windowsserver2003/technologies/management/powershell/download.
mspxWindowsPowerShell1.
0ofciallysupportsWindowsXPServicePack2,WindowsServer2003,WindowsVista,andWindowsServer2008.
WindowsPowerShell2.
0wasreleasedwiththeWindows7andWindowsServer2008R2operatingsystems.
PowerShell2.
0willbeeventu-allypack-portedtootheroperatingsystemsaswell.
WhenyourstlaunchWindowsPowerShellinyoursystemandimporttheVMMPow-erShellsnap-in,youwillbepromptedtoaddMicrosoftCorporationtothelistoftrustedpublishers,asperFigure8.
1.
EnterAinthiscaseforAlwaysRun.
Figure8.
1AddingMicrosoftCorporationtothelistoftrustedpublishersforWindowsPowerShellscriptsItispossibleWindowsPowerShellwillstillpreventyoufromrunningscriptsinyoursystem,soyouneedtosettheproperexecutionpolicyforscriptsbeforeanyWindowsPowerShellscriptsareallowedtorunonyourcomputer.
ThiscanbeachievedusingtheSet-ExecutionPolicycmdlet.
Figure8.
2showsthehelpcontentsofthiscmdlet.
Typeinget-helpSet-ExecutionPolicy-detailed|moreformoreinformationonthepolicyoptions.
ToinvoketheSet-ExecutionPolicycmdlet,youneedtorunWindowsPowerShellasAdministrator.
VMMANDWINDOWSPOWERSHELL329Figure8.
2SettingtheexecutionpolicyforWindowsPowerShellExposingtheVMMCmdletsTogetstartedwithVMMandWindowsPowerShell,openaconsolewindowthathastheVMMPowerShellsnap-inloaded.
Thereareafewwaystoaccomplishthis,asshownhere:1.
ClickStartAllProgramsMicrosoftSystemCenterVirtualMachineManager2008R2andlaunchWindowsPowerShell-VirtualMachineManager.
Thiscommandwillauto-maticallylaunchWindowsPowerShellversion1.
0andpassasinputtheVMMPowerShellConsolelelocatedat%SystemDrive%\ProgramFiles\MicrosoftSystemCenterVirtualMachineManager2008R2\bin\cli.
psc12.
OpenaregularWindowsPowerShellconsolewindowandaddtheVMMsnap-inusingthefollowingcommand.
OncetheVMMsnap-inisadded,youcanusealltheVMMcmdlets.
Add-PSSnapin"Microsoft.
SystemCenter.
VirtualMachineManager"3.
WindowsPowerShellcanalsobelaunchedfromtheAdministratorConsolebyclickingthePowerShellbuttoninthetoolbarofthemainview.
330CHAPTER8AUTOMATIONUSINGPOWERSHELLOncetheVMMPowerShellsnap-inisadded,youcangetalistofallVMMcmdletsusingtheget-commandcmdlet.
#Thiscmdletwillgetallcmdletsthatcanbeexecutedbythecurrently#loadedPowerShellsnapinsGet-command#ThiscmdletwilllistonlythecmdletsexposedbytheVMMWindows#PowerShellsnapinget-command-module"Microsoft.
SystemCenter.
VirtualMachineManager"GettingHelponVMMCmdletsIfyouhavethenameofaVMMcmdlet,youcangetmoreinformationonit,includingalistofexamples.
ThefollowingcodeshowshowtogetthedenitionoftheRefresh-VMcmdlet:PSD:\>get-commandrefresh-vmCommandTypeNameDefinitionCmdletRefresh-VMRefresh-VM[-VM][-RunA.
.
.
ThefollowingcodeshowshowtogetthedetailedviewoftheparametersthatcanbepassedtotheRefresh-VMcmdlet:PSD:\>get-commandrefresh-vm|format-listName:Refresh-VMCommandType:CmdletDefinition:Refresh-VM[-VM][-RunAsynchronously][-JobVariable][-PROTipID][-Verbose][-Debug][-ErrorAction][-WarningAction][-ErrorVariable][-WarningVariable][-OutVariable][-OutBuffer]Path:AssemblyInfo:DLL:D:\ProgramFiles\MicrosoftSystemCenterVirtualMachineManager2008R2\bin\Microsoft.
SystemCenter.
VirtualMachineManager.
dllHelpFile:Microsoft.
SystemCenter.
VirtualMachineManager.
dll-Help.
xmlParameterSets:{[-VM][-RunAsynchronously][-JobVariable][-PROTipID][-Verbose][-Debug][-ErrorAction][-WarningAction][-ErrorVariable][-WarningVariable][-OutVariable][-OutBuffer]}ImplementingType:Microsoft.
SystemCenter.
VirtualMachineManager.
Cmdlets.
RefreshVmCmdletVMMANDWINDOWSPOWERSHELL331Verb:RefreshNoun:VMThefollowingcodeshowshowtogetthehelpfortheRefresh-VMcmdlet:PSD:\>get-helprefresh-vmNAMERefresh-VMSYNOPSISRefreshesthepropertiesofavirtualmachinesothattheVirtualMachineManagerAdministratorConsoledisplaysupdatedinformationaboutthevirtualmachine.
SYNTAXRefresh-VM[-VM][][-JobVariable][-PROTipID][-RunAsynchronously][]DETAILEDDESCRIPTIONRefreshesthepropertiesofavirtualmachinesothattheVirtualMachineManagerAdministratorConsoledisplaysupdatedinformationaboutthevirtualmachine.
TheupdatedpropertiesincludeName,Location,Status,OperatingSystem,andotherproperties.
RELATEDLINKSGet-VMRefresh-LibraryShareRefresh-VMHostREMARKSToseetheexamples,type:"get-helpRefresh-VM-examples".
Formoreinformation,type:"get-helpRefresh-VM-detailed".
Fortechnicalinformation,type:"get-helpRefresh-VM-full".
Thenextcodeshowsthedifferentparametersthatcanbepassedtotheget-helpcmdlet:#Toshowdetailedinformationontherefresh-vmcmdlet,usethe#-detailedparameterPSD:\>get-helpRefresh-VM-detailed#Thiscommandwillshowexamplesonusingthecmdletrefresh-vmPSD:\>get-helpRefresh-VM-examples#Thiscommandwillshowthefullinformationonusingtherefresh-vmcmdletPSD:\>get-helpRefresh-VM-fullSomeVMMcmdletsofferdifferentparameterssets.
InFigure8.
3andFigure8.
4,youcanseethedifferentparametersetsfortheGet-VMcmdlet.
Forexample,youcangeta332CHAPTER8AUTOMATIONUSINGPOWERSHELLlistofvirtualmachines(VMs)byamatchingname,byusingtheIDoftheVMobject,orbyexecutingthecmdletagainstaspecichost.
Anyparameterthatisincludedinsquarebracketsisoptional.
Ifarequiredparameterisnotspecied,PowerShellwillpromptforitasFigure8.
5shows.
Figure8.
3Get-VM'sdifferentparametersetsUsingtheVMMCmdletsBynowyouknowhowtogetalistofallVMMcmdletsandtheirdescriptions.
Togetmoreinformationabouteachcmdlet,includingdetailsoneachparameterandexamplesonhowtoinvokethem,youcanusetheget-helpcmdletwiththe-full,-examples,or-detailedparameter.
VMMANDWINDOWSPOWERSHELL333Figure8.
4Get-VM'srequiredparametersFigure8.
5WindowsPowerShellwillpromptforrequiredparameters.
334CHAPTER8AUTOMATIONUSINGPOWERSHELLTheVirtualMachineManagerScriptingGuideisalsoagreatreferenceforlearninghowtouseWindowsPowerShellwithVMM.
VMMpublishedascriptingguidewithbothVMM2007andVMM2008.
Youcanndthescriptingguidesathttp://www.
microsoft.
com/downloads/details.
aspxfamilyid=3DA5BA7E-AD72-4D2C-B573-1B74894D1DDF&displaylang=enandathttp://technet.
microsoft.
com/en-us/library/cc764259.
aspx.
AscriptingguideupdateforVMM2008R2shouldbeavailableontheSystemCenterVirtualMachineManagerTechCentershortly.
AppendixB,''VMMWindowsPowerShellObjectPropertiesandVMMCmdletDescrip-tions,''containsareferencelistofVirtualMachineManagercmdletsandashortdescriptionoftheirfunctionality.
NounPropertiesWindowsPowerShellusesaverb-nounformatforthenamesofthecmdlets.
Theverbidentiestheactiontobeperformed,suchasget,add,set,remove,ornew.
TheWindowsPowerShellteamhasapublishedlistofcommonverbsforcmdletdeveloperstoadhereto.
Thenounidentiesthetypeofobjectonwhichthecmdletwilloperate.
ExamplenounsincludeVM(virtualmachine),VMHost(virtualizationhost),VMHostCluster(FailoverCluster),andVirtualNetwork(virtualnetwork).
Inthissection,wewilllookatthreeofthemostfre-quentlyusednounsinVMMandexplaintheirpropertyvalues.
VMMcmdletswillinmostcasesreturnbacktothepipelinethenounofthecmdlet.
ThisallowsyoutousethepipelineandcombinemultipleVMMcmdletsformorecomplicatedscripts.
ForGet-*cmdlets,likeGet-VMforexample,itispossibleforthevaluethatisreturnedtothepipelinetobeacollectioninsteadofasingleobject.
Youcancheckthetypeofthereturnvalueusingthecodesnippetinthenextparagraph.
PowerShellPipelineThePowerShellpipelineissimilarinconcepttothe''pipeline''seeninUnixshellscript-ingenvironments.
Thepipelineallowsyoutocreateamultitudeofsingle-purposeandeasy-to-understandcmdletsandthencombinethemtoachieveabiggertask(justlikebuildingblocks).
ThefollowingcodeshowshowtoinvoketheGet-VMcmdletandchecktheresult:#ExecuteGet-VMonaVMthatdoesnotexist.
Inthiscase$vmshouldbenull$vm=Get-VM"VMDoesNotExist"$vm-eq$null#ExecuteGet-VMasatargetedgetforasingleVM.
Inthiscase#theresultshouldnotbeanarray$vm=Get-VM"virtualmachine1"$vm-is[Array]#ExecuteGet-VMtogetallVMsinthesystem.
Inthiscasethe#resultmaybeanarray$vm=Get-VM$vm-is[Array]VMMANDWINDOWSPOWERSHELL335VMMServerObjectVMMServerrepresentstheobjectthatcontainstheconnectiontotheVirtualMachineManager.
ThisobjectalsocontainssomeoftheglobalsettingsoftheVMMserverinstallationandenvironment.
OnceaconnectiontotheVMMserverisestablished,theconnectioniscachedandfuturecmdletsthatneedaconnectionobjectwillautomaticallyusetheexistingcachedconnection.
ToseetheVMMServernounandalistofitspropertieswithanexplanationforeachproperty,seeAppendixB.
VMObjectVMrepresentstheobjectthatcontainsavirtualmachineinstanceinVirtualMachineManager.
Toseethevirtualmachinenounanditsproperties,seeAppendixB.
Eachpropertyalsocon-tainsadenitionforitsvalueorvalues.
VMHostObjectVMHostrepresentstheobjectthatcontainsaphysicalcomputerthatisavirtualmachinehost.
AvirtualmachinehostcouldbeaVirtualServerhost,aHyper-Vhost,oraVMwareESXhost.
Thefollowingcodeshowsyouhowtogetalistofallthepropertiesofahostandinspecttheirvalues:PSD:\>$vmhost=Get-VMHost"hostname"PSD:\>$vmhostWindowsPowerShellwilloutputallthepropertiesandvaluesforthesuppliedhost.
ToseetheVMHostnounanditsproperties,seeAppendixB.
Eachpropertyalsocontainsadenitionforitsvalueorvalues.
LeveragingthePublicPowerShellAPIVirtualMachineManagerusestheWindowsPowerShellcmdletsforVMMasthesinglepointofentryforVMM.
DeveloperscanintegratewithVMMprogrammaticallybyleveragingthepubliclyavailableVMMPowerShellcmdlets.
CallingcmdletsprogrammaticallyisnotmuchdifferentthaninvokingtheminaWindowsPowerShellcommandwindow.
Inthissection,wewilllookatprogrammaticallyinvokingthecmdletsandgiveyouexamplecodetoachievethistypeofintegrationwithVMM.
ProgrammaticallyCallingtheVMMCmdletsThesetofWindowsPowerShellcmdletsforVMMistheonlysupportedAPIforintegratingwithVMM.
ToprogrammaticallycallthecmdletsandmanageVMM,youwouldneedtocreateaPowerShellrunspaceandinvokethecmdletsinthesamewayyouwouldifyouwereusingtheWindowsPowerShellcommandwindow.
Tostart,youneedtoknowthepathtotheVMMassembliesthatareneededtoresolvetheVMMobjectsandcmdlets.
YoucanndtheinstallationpathfortheVirtualMachineManagerAdministratorConsoleundertheRegistrykeyHKLM\Software\Microsoft\MicrosoftSystemCenterVirtualMachineManagerAdministratorConsole\Setup.
TheInstallPathvalueof336CHAPTER8AUTOMATIONUSINGPOWERSHELLthisRegistrykeycontainstherootoftheinstallationpathforVMM.
ThefourassembliesthatareneededfortheprogrammaticusageofVMMcmdletsarelocatedinthebinfolderoftheinstallationdirectory.
Thesebinariesarelistedhere:Microsoft.
SystemCenter.
VirtualMachineManager.
dllRemoting.
dllUtils.
dllErrors.
dllBecausenoneoftheseVMMassembliesarelistedintheGlobalAssemblyCache(GAC),ifyouwantyourapplicationtobeabletoresolvethemwithoutcopyingthebinaries,youneedtouseanassemblyresolvehandler.
Thefollowingcodeshowsyouhowtoaddsuchahandlerandhowtoproperlyloadthecorrectassembly.
TheInstallPathvaluefromtheRegistryisneededforthispurpose://AddthecodefortheassemblyresolverbeforeanyoftheVMMbinariesareinvoked.
Thread.
GetDomain().
AssemblyResolve+=newResolveEventHandler(VMMResolveEventHandler);//Inthisexample,weautomaticallyresolveeverythingtotheVirtualMachineManagerDLL.
Asmartresolverwouldlookattheargs.
Nameandmatchtheassemblytoberesolvedwithitsproperfullpath.
staticAssemblyVMMResolveEventHandler(objectsender,ResolveEventArgsargs){returnAssembly.
LoadFrom("D:\ProgramFiles\MicrosoftSystemCenterVirtualMachineManager2008R2\bin\Microsoft.
SystemCenter.
VirtualMachineManager.
dll");}Inadditiontotherequiredbinaries,theWCFportnumberoftheVMMserverisneededtoestablishasuccessfulconnection.
YoucanndtheTCPportnumberforWCFundertheVMMserverRegistrykeyHKLM\Software\Microsoft\MicrosoftSystemCenterVirtualMachineManagerServer\Settings.
TheIndigoTcpPortvaluecontainstheportnumberthatallVMMclientsneedtousetoconnect.
NowwehaveallthedataweneedtoconnecttoVMMandexecutesomePowerShellcmdlets.
ItisrecommendedtouseautilitytocreateawrapperontopoftheVMMPowerShellsnap-in.
Suchawrapperwouldproduceafamiliar.
NETinterfacefordevelopersandprovidetypesafetyforallPowerShellcmdlets.
Thereareafewpubliclyavailabletoolstocreatesuchwrappers.
Inthefollowingexample,IamusingthenativePowerShellimplementation,directlyinvokingcmdletsusingtheirstringnames.
Youcanseethatanymistakesinthiscodewillnotbecaughtbythecompiler.
Listing8.
1isacompleteprogramthatcreatesaPowerShellrunspace,addstheVMMPower-Shellsnap-intoit,createsaconnectiontotheVMMserverondefaultport8100,andgetsalistofallVMsthatthecurrentuserisauthorizedtosee.
ThelistofVMsreturnediswrittenontheconsolewindowasinFigure8.
6.
VMMANDWINDOWSPOWERSHELL337Figure8.
6OutputfromtheprogrammaticinvocationofGet-VMListing8.
1:InvokingtheVMMcmdletsprogrammatically//AddthepropernamespacesusingSystem;usingSystem.
Management.
Automation;usingMicrosoft.
VirtualManager.
Utils;usingMicrosoft.
SystemCenter.
VirtualMachineManager;usingMicrosoft.
SystemCenter.
VirtualMachineManager.
Cmdlets;usingMicrosoft.
SystemCenter.
VirtualMachineManager.
Remoting;usingMicrosoft.
VirtualManager.
Remoting;usingSystem.
Management.
Automation.
Runspaces;usingSystem.
Collections.
ObjectModel;namespaceConsoleApplication{classProgram{staticvoidMain(string[]args){//CreateadefaultRunspaceConfigurationRunspaceConfigurationconfig=RunspaceConfiguration.
Create();//AddtheVMMPowerShellsnapinPSSnapInExceptionwarning=null;config.
AddPSSnapIn("Microsoft.
SystemCenter.
VirtualMachineManager",outwarning);if(warning!
=null){Console.
WriteLine(warning.
Message);return;}338CHAPTER8AUTOMATIONUSINGPOWERSHELL//CreatetheRunspaceusingthisconfigurationRunspacerunspace=RunspaceFactory.
CreateRunspace(config);try{runspace.
Open();CommandpsCommand=null;ServerConnectionserverConnection=null;VMvmObject=null;//CreateaPipelineusing(Pipelinepipeline=runspace.
CreatePipeline()){//Calltheget-vmmservercmdlettogetaconnectiontoVMM//IfyouplantouseVMMasaplatformanddevelop//aseparateGUIontopofVMM,youmightalsowantto//settheRetainDeletedObjectsandRetainObjectCache//propertiesoftheGet-VMMServercmdlet.
Formore//informationontheseproperties,lookatthehelp//forthecmdlet.
psCommand=newCommand("Get-VMMServer");psCommand.
Parameters.
Add("ComputerName","localhost");psCommand.
Parameters.
Add("TCPPort","8100");pipeline.
Commands.
Add(psCommand);//InvokethecmdletCollectionpsObjList=pipeline.
Invoke();serverConnection=(ServerConnection)(psObjList[0].
BaseObject);}//CreateaPipelineusing(Pipelinepipeline=runspace.
CreatePipeline()){//Calltheget-vmcmdlettogetallVMsinthesystempsCommand=newCommand("Get-VM");pipeline.
Commands.
Add(psCommand);//InvokethecmdletCollectionpsObjList=pipeline.
Invoke();//Enumeratetheresultsofthecmdletforeach(PSObjectobjinpsObjList){vmObject=(VM)obj.
BaseObject;Console.
WriteLine("VMName:{0},ID:{1}",vmObject.
Name,vmObject.
ID);VMMANDWINDOWSPOWERSHELL339}}}finally{//Closetherunspaceifitisalreadyopenif(runspace.
RunspaceStateInfo.
State==RunspaceState.
Opened){runspace.
Close();}}}}}WhentryingtoprogrammaticallycodeagainstVMM,itisusefultounderstandandknowallthedifferentvaluesandpropertiesforthevariousVMMclassesandenumerations.
Togetfamiliarwiththenounsandtheirproperties,youcanloadtheMicrosoft.
SystemCenter.
VirtualMachineManager.
dllintotheObjectBrowserofVisualStudioandstartlookingintotheclassesdenedinthisassembly.
ThefollowingcodesnippetshowstheStatuspropertyofavirtualmachineobjectasdenedbytheVMclass.
Figure8.
7showsthelistofpossiblevaluesfortheVMComputerSys-temStateenumeration.
publicclassVM{publicVMComputerSystemStateStatus{get;}}TheHostclasshasmultiplestateobjects.
Inthefollowingcodesnippet,alongwithFigure8.
8andFigure8.
9,weshowyouhowtogettheCommunicationStateandtheComputerStateofahostobjectandthepossiblevaluesforthetwoenumerations.
publicclassHost{publicCommunicationStateCommunicationState{get;}publicComputerStateComputerState{get;}}CreatingPowerShellScriptsPowerShellscriptsaresimpletextlesthatyoucanauthorinNotepadandsavewiththele-nameextension.
ps1.
YoucanalsochoosetodownloadaPowerShellinteractivedevelopmentenvironment(IDE).
SuchanIDEwillacceleratedevelopmentthroughrichsyntaxcoloring,IntelliSense,tabbing,andrichdebugging.
340CHAPTER8AUTOMATIONUSINGPOWERSHELLFigure8.
7Gettingthestateenu-merationforaVMFigure8.
8Gettingthecommunica-tionstateenumerationforaHostVMMANDWINDOWSPOWERSHELL341Figure8.
9GettingthecomputerstateenumerationforaHostTocreateaPowerShellscriptle,followtheseinstructions:1.
OpenNotepad.
exeoryourfavoriteeditor.
2.
AddthePowerShellcmdletsyouwantthescripttoexecute.
Forexample,Get-VM|Refresh-VM.
3.
SavetheleasRefreshVirtualMachines.
ps1.
OnceyouhavecreatedyourPowerShellscriptle,youcaninvokeitbyusingthefullpathtotheleinPowerShell.
IfthefollowingcodesnippetfailsduetothePowerShellexecutionpolicy,refertoFigure8.
2formoreinformation:PSD:\>.
\demo.
ps1ThisisademoscriptPassingparameterstoaPowerShellscriptissimilartopassingtheminotherscriptinglan-guages.
Insidethescript,youcanusethe$argsvariabletogettheparameterspassedtothescript:PSD:\>.
\demo.
ps13parameterspassedThisisademoscriptParameter#1:3Parameter#2:parametersParameter#3:passedEventhoughcreatingPowerShellscriptsiseasy,debuggingscriptsisharderthandebuggingindividualcmdlets.
Itisrecommendedtotryyoursequenceofcmdletsintheinter-activeWindowsPowerShellwindowandmakesuretheyworkbeforeputtingeverythinginascriptle.
342CHAPTER8AUTOMATIONUSINGPOWERSHELLWindowsPowerShellandtheAdministratorConsoleInadditiontothedocumentationontheVMMcmdlets,theVirtualMachineManagerAdmin-istratorConsoleprovidesafewotherwaystogetfamiliarwithPowerShellandVMM.
TheadditionalfeaturesforenhancingyourPowerShellknowledgeareinthefollowinglist:ViewingthePowerShellscriptthatVMMwillexecuteAllVMMwizardsintheAdminis-tratorConsolehaveaViewScriptbuttoninthelastwizardpage.
ClickingitopensupNotepadandshowsyoutheWindowsPowerShellcmdletsthatVMMwillinvoketoexecutetheactionstheuserchoseinthewizard.
Figure8.
10hasanexamplescriptthatwasgeneratedduringthemigrationofaVMfromonehosttoanother.
ThisisagreatwaytostartlearningmoreaboutPowerShellandautomatingsomeoftheactionsthatVMMprovidesinthewizardpages.
Figure8.
10TheViewScriptbuttonattheendofthemigrationwizardandanexamplescriptViewingthePowerShellcmdletequivalentforaVMMjobTheAdministratorConsole'sjobsviewhasacolumnthatliststheVMMcmdletusedforeachVMMjobthatchangesdata(forexample,theGet-*cmdletswillnothaveanentryinthisviewsinceaVMMjobisnotcre-atedforsuchcmdlets).
Eachjobhasafriendlynamethatindicatestheactionperformed,andyoucangetmoreinformationonthespeciccmdletinvokedthroughtheGet-Helpcmdlet.
Figure8.
11showsyoualistofVMMjobsandtheirassociatedcmdletnames.
Theresulttypethatislistedindicatesthetypeofobjectonwhichthisoperationwasperformed.
Thisisusuallythenounofthecmdlet.
VMMlibrarysupportforWindowsPowerShellscriptsTheVMMlibraryhasbuilt-insup-portforPowerShellscripts.
Youcanplaceallyourleswiththe.
ps1lenameextensioninthelibrarysharesandVMMwillautomaticallyimportthemintothelibraryview.
Fromthelibrary,youcanviewandeditthescripts(editingthePowerShellScriptsrequiresthattheuseroftheAdministratorConsolehaswritepermissionsonthelibraryshareandtheassociatedPower-Shellscriptle),oryoucanexecutethescriptsasperFigure8.
12.
ThroughtheRunPowerShellScriptactionoftheVMMlibrary,VMMwilllaunchanewWindowsPowerShellprocessandinvokethisPowerShellscript.
BecauseVMMexecutesyourscriptafteritobtainsaconnectiontotheVMMserver,youdon'tneedtoexecuteGet-VMMServeratthebeginningofyourscript.
VMMwillalsokeepthePowerShellwindowopenforinspectingtheresults.
VMMANDWINDOWSPOWERSHELL343Figure8.
11TheCommandcolumninthejobsviewoftheAdministratorConsoleFigure8.
12PowerShellscriptsintheVMMlibraryInterfacingwithHyper-VandVirtualServerHyper-Vhasawell-documentedWMIAPIthatcanbeaccessedfromtheMicrosoftDeveloperNetwork'swebsite.
ItislistedundertheVirtualizationWMIProviderdocumentation,andthenamespacefortheWMIisroot\virtualization.
TheWMIproviderishostedbytheHyper-VVirtualMachineManagementWindowsService.
ThefollowingcodeshowshowtogetallvirtualMachinesfromaHyper-VserverusingWindowsPowerShellandtheWMIAPIforHyper-V:#GetlistofVirtualMachineandhostmachinefromHyper-VWMIAPI$computerlist=get-wmiobjectMsvm_ComputerSystem-namespaceroot\virtualization344CHAPTER8AUTOMATIONUSINGPOWERSHELL#ShowintabularformatthelistofVMsandHost#(Hostisidentifiedinthecaptionas"HostingComputerSystem")#TheNameforVirtualMachinescontainstheuniqueGUIDthatidentifiesaVM#ElementNamecontainstheuser-friendlynameoftheVM$computerlist|selectName,ElementName,CaptionAsimplewaytotestWMIqueriesbeforeexecutingtheminWindowsPowerShellisthroughthewbemtestutility.
Thisutilityisinstalledinthe%SystemDrive%\Windows\System32\wbem\Windowsfolder.
ToexecuteaWMIqueryusingthisutility,followthesesteps:1.
Launchwbemtest.
exe.
2.
ClickConnectandtyperoot\virtualizationintheNamespaceeld.
3.
ClickQueryandtypeaWMIquery,suchasselectName,ElementName,CaptionfromMsvm_ComputerSystem4.
TheresultswillincludethesamelistastheprecedingPowerShellexample.
ClickoneachindividualresulttoseetheName,ElementName,andCaptionvalues.
VirtualServer'sCOMinterfaceisdocumentedontheMicrosoftDeveloperNetworkunderthetitleofMicrosoftVirtualServerReference.
TobeabletoinvokethisAPIusingPowerShell,youneedtomeetthesecurityprerequisites.
Bydefault,PowerShelldoesnothavethenecessaryCOMsecurityleveltoinvoketheVirtualServerCOMAPI.
Toaccomplishthat,followthesesteps:1.
CreateanewlibraryDLLthatallowsyoutosettheCOMsecurityleveltoImper-sonateforanyCOMobject.
Toaccomplishthis,addanewAPItothelibraryDLLcalledSetVSSecurity.
InthisAPI,youneedtoinvokeCoSetProxyBlanketwiththeRPC_C_IMP_LEVEL_IMPERSONATEparameterfortheCOMobjectthatispassedasaparameter.
2.
OnceyoucreatethisDLL,youcanusetheSystem.
Reflection.
Assembly.
LoadFrom().
NETAPIandpasstheDLL'sfullpathasaparameter.
3.
OnceyouhaveaVirtualServerobjectinPowerShell,youneedtoinvoketheAPIfromthisDLLtosettheCOMsecuritytoImpersonatesothattheobjectcanbeused.
TheAPISetVSSecurityshouldtakeaPowerShellobjectasaparameter.
4.
Youmightneedtosetotherobjects'COMsecurityaswell,asyoustartworkingwithVir-tualServerandPowerShell.
Forexample,theVMobjectwillneedtohaveitsCOMsecurityelevatedtoImpersonatebeforeitcanbeused.
ThefollowingcodeshowshowtogettheVirtualServerrootobjectusingPowerShell.
#CreateanewVirtualServerCOMinstance$VirtualServer=new-object–comVirtualServer.
Application–Strict#NowsettheCOMsecurityofthe$VirtualServerobjectto"Impersonate"#andthenyoucanusethisobjecttomanageVirtualServer[FullnamespacepathfortheDLLcreatedinstep1above]::SetVSSecurity($VirtualServer)AUTOMATINGCOMMONTASKSUSINGTHEWINDOWSSCHEDULER345#Aftersettingthepropertyof$VirtualServerto"Impersonate",youcan#getalistofVirtualMachinesandusethefullCOMAPIof#VirtualServerAutomatingCommonTasksUsingtheWindowsSchedulerITpersonneltodayspendalotoftimeonrepetitivetaskstoaccomplishvariousjobs.
Pow-erShellprovidesapowerfullanguagethatcanbeusedtowriteandexecutescripts.
Thesescriptscaneliminaterepetitivetasksandaddthenecessarylogictocompletecomplexjobs.
SinceVMMisbuiltentirelyontopofPowerShell,anythinganadministratorcandointheAdministratorConsolecanalsobeaccomplishedviaPowerShellcmdlets.
Ifyoucombinethatwiththeabilitytointegratewith.
NETandotherdatastoresthatarePowerShellready,anadministratorshouldbeabletotranslatealotofmanualworkintoPowerShellscripts.
TheabilitytoschedulePowerShellscriptsatspeciedintervalsallowsanadministratortodopassivemanagementoftheirsystemandletPowerShelldosomeoftheheavyliftingduringnonworkinghours.
OnceyouhaveaPowerShellscriptready,youmaywanttoexecuteitatregularintervalsandcaptureitsresultsinalogle.
IfthecmdletschangedatainVMM,youcanalsoviewtheresultsintheAdministratorConsole'sjobsview.
Thereareacoupleofwaystocreateasched-uledtaskinWindowsServer.
Inthissection,wewillshowyouhowtodothisfromtheTaskScheduleruserinterface.
Optionally,youcanusetheschtasks.
exeutilitytocreateascheduledtask.
ToscheduleataskfromtheTaskScheduler,followthesesteps:1.
OpentheTaskSchedulerMMCsnap-in.
TaskSchedulerislocatedineitherControlPanel\SystemandSecurity\AdministrativeTools\TaskSchedulerorControlPanel\AdministrativeTools\TaskScheduler,dependingontheversionofWindowsinstalled.
2.
SelectCreateTask.
3.
EnteraTaskNamelikeWindowsPowerShellautomatedscript.
4.
SelectRunWhetherUserIsLoggedOnOrNotandchosetostorethepassword.
5.
SelectChangeUserOrGrouptoenterauserthathastheproperVMMprivilegestoexecutethisPowerShellscript.
6.
IntheTriggerstab,enterthescheduleyouwouldliketocreateforthisscheduledtask.
Forexample,youcanchosetorunthisscriptdailyat8p.
m.
7.
IntheActionstab,asshowninFigure8.
13,addanewactionandselectStartAProgram.
Intheprogrampath,enterD:\Windows\System32\WindowsPowerShell\v1.
0\powershell.
exe.
ThisisthefullpathtoWindowsPowerShell1.
0.
Forarguments,enterthefollowing:-PSConsoleFile"D:\ProgramFiles\MicrosoftSystemCenterVirtualMachineManager2008R2\bin\cli.
psc1"-Command"&'\\hypervhost1.
vmmdomain.
com\MSSCVMMLibrary\Scripts\GetVMStatus.
ps1'"-NoProfile-Noninteractive346CHAPTER8AUTOMATIONUSINGPOWERSHELLIfyouweretoexecutethiscommandfromaregularcommandwindow,itwouldlooklikethis:D:\Windows\System32\WindowsPowerShell\v1.
0\powershell.
exe-PSConsoleFile"D:\ProgramFiles\MicrosoftSystemCenterVirtualMachineManager2008R2\bin\cli.
psc1"-Command"&'\\hypervhost1.
vmmdomain.
com\MSSCVMMLibrary\Scripts\GetVMStatus.
ps1'"-NoProfile-Noninteractive8.
ClickOKandenterthepasswordfortheaccountthatwillexecutethescheduledtask.
9.
FromtheTaskSchedulerMMC,youcanviewallyourscheduledtasks,checkfortheirlastruntime,andseeiftherewereanyerrorsinexecutionbasedonthelastrunresult.
Figure8.
13AddingthescheduledtaskactionSometimes,itiseasiertocheckifascheduledtaskisexecutingbylookingatalogle.
ThefollowingsamplePowerShellscriptshowsyouhowtologthatinformationtoale:Write-Output"Scriptexecutingat"(date)#GetaconnectiontothelocalVMMserver$c=get-vmmserverlocalhost#MakeasamplequerytogetsomedatafromVMM$results=get-vm|selectname,status,vmid,ID,hostnameWINDOWSPOWERSHELLEXAMPLES347#Createalogfileinthetempdirectory$filepath="$env:temp\PSscriptOutput.
log"#AppendtothelogfilethecurrenttimeandthedataretrievedfromVMMAdd-Content(date)-Path$filepathAdd-Content$results-Path$filepathAdd-ContentPath$filepathBecausescheduledPowerShellscriptsdon'tofferthesamedegreeofdebugging,youneedtoensurethattheproperexecutionpoliciesareinplaceforPowerShellscripts.
Itisrecom-mendedthatallscriptsyouexecuteusingtheTaskScheduleraresignedusingacodesigningcerticateissuedbyacerticateauthority.
ThiswillenableyoutosetthePowerShellexecu-tionpolicytoamoresecurelevelliketheAllSignedoption.
AfteryousignascriptusingtheSet-AuthenticodeSignaturecmdlet,youwillneedtoaddthepublisherofthescripttoyourtrustedpublishers.
PowerShellwillpromptyoutodothatontherstexecutionofthescript.
InChapter9,''WritingaPROPack,''wewillcoverthePROfeatureofVMM.
PROallowsanadministratortoexecuteaPowerShellscriptorperformaVMMactionbasedonasetofalertsdetectedbySystemCenterOperationsManager(OpsMgr).
OpsMgrisacomprehensivedatacentermonitoringtool.
Inthiscase,aPowerShellscriptisexecutedinresponsetoadynamicevent.
WindowsPowerShellExamplesInthefollowingsections,wewilllistafewdifferentWindowsPowerShellscriptsthatleveragetheVMMcmdletstoaccomplishimportanttasksinVMM,makeiteasierforanadministratortoexecuterepetitiveactions,andallowanadministratortogetquickstatusonthehealthofVMMobjects.
CreatingVirtualMachinesTherearemanywaystocreateavirtualmachineinVMM.
Inthissection,wewilltakealookatanexampleofhowtocreateahighlyavailable(HA)VMandndthebestsuitablehostonwhichtoplaceit.
ThebestsuitablehostisfoundbytheIntelligentPlacementfeatureofVMMbasedonthepropertiesoftheVMandtheavailablehosts.
Listing8.
2containsthecodeforcre-atingtheHAvirtualmachine.
Listing8.
2:Creatinganewhighlyavailablevirtualmachine#GetaconnectiontotheVMMserver$c=Get-VMMServer"localhost"#CreatetheJobGroupID.
ThisistheGuidthatpairsallthecmdlets#necessarytoensurethatthenewVirtualMachinecreationis#Successful.
EverycmdletthatspecifiesthesameJobGroupIDwill#bepartofasetandwillbeexecutedinorderafterthefinalcommand#thatincludesthesameJobGroupIDruns.
Inthiscase,thefinal348CHAPTER8AUTOMATIONUSINGPOWERSHELL#commandistheNew-VMcmdlet.
$JobGroupID=[System.
Guid]::NewGuid().
ToString()#EntertheVMName$VMName="virtualmachine1"#CreateavirtualNICNew-VirtualNetworkAdapter-JobGroup$JobGroupID-PhysicalAddressTypeDynamic-VLANEnabled$false#CreateavirtualDVDNew-VirtualDVDDrive-JobGroup$JobGroupID-Bus1-LUN0#CheckifanotherHWprofilehasthesamenameanddeleteitifthereis$HardwareProfile=Get-HardwareProfile|where{$_.
Name-eq"HWProfile"}if($HardwareProfile-ne$null){Write-Warning"Deletingtheexistinghardwareprofilewiththesamename"Remove-HardwareProfile$HardwareProfile}#Createanewhardwareprofilewiththeuserpreferences#The-HighlyAvailablepropertyofthiscmdletistheoneindicating#thatthisVirtualMachineshouldbeaHighlyAvailableone$HardwareProfile=New-HardwareProfile-Owner"vmmdomain\administrator"-Name"HWProfile"-CPUCount1-MemoryMB2048-HighlyAvailable$true-NumLock$false-BootOrder"CD","IdeHardDrive","PxeBoot","Floppy"-LimitCPUFunctionality$false-JobGroup$VMGuid#CreateanewVHDfortheVM$DiskDrive=New-VirtualDiskDrive-IDE-Bus0-LUN0-JobGroup$JobGroupID-Size10240-Dynamic-Filename"virtualmachine1.
vhd"#GetallthehostsandtheirratingsforthisVM'sHWprofile$AllHosts=Get-VMHost$hostrating=Get-VMHostRating-VMHost$AllHosts-HardwareProfile$HardwareProfile-DiskSpaceGB10-VMName$VMName#Orderthehostratingsandcheckifwehaveatleastone#positivestarratingforthisVM$orderedrating=$hostrating|sort-objectrating-descendingWrite-Output$orderedrating#Iftheratingis0,exitanddon'tcallnew-vmif($orderedrating-is[Array]){#wehavemultipleresults,sopickthetopone$targethost=$orderedrating[0].
VMhostWINDOWSPOWERSHELLEXAMPLES349if($orderedrating[0].
Rating-eq0){Write-Warning"ThereisnosuitablehostforthisVM'sprofile"Write-Warning$orderedrating[0].
ZeroRatingReasonList[0]break}}else{$targethost=$orderedrating.
VMhostif($orderedrating.
Rating-eq0){Write-Warning"ThereisnosuitablehostforthisVM'sprofile"Write-Warning$orderedrating.
ZeroRatingReasonList[0]break}}Write-Output"WewillbecreatinganewVMonhost$targethost"#GettheoperatingsystemfromalistofpredefinedOSNamesinVMM$OperatingSystem=Get-OperatingSystem|where{$_.
Name-eq"64-biteditionofWindowsServer2008Enterprise"}#FindthepathfortheLUN/DisktohostthefilesforthenewHAVM#Makesurethisvolumeisnotinuse,isaclustervolume#(withclusterresourcesalreadycreated),andisavailable#forplacement$targetpath=get-vmhostvolume-VMHost$targethost|where-object-filterscript{$_.
IsClustered-eq$true}|where-object-filterscript{$_.
InUse-eq$false}|where-object-filterscript{$_.
IsAvailableForPlacement-eq$true}if($targetpath-eq$null){Write-Warning"ThereisnosuitableclusterdisktoplacethisVMon"Break}if($targetpath-is[Array]){#PickthefirstavailabledisktoplacethisVMon$targetpath=$targetpath[0].
Name}else{$targetpath=$targetpath.
Name}350CHAPTER8AUTOMATIONUSINGPOWERSHELL#Createthenew-vminanasynchronouswayNew-VM-VMMServer$c-Name$VMName-Description"newHAVMtolearnmoreaboutPowerShell"-Owner"vmmdomain\administrator"-VMHost$targethost-Path$targetpath-HardwareProfile$HardwareProfile-JobGroup$JobGroupID-RunAsynchronously-OperatingSystem$OperatingSystem-RunAsSystem-StartActionNeverAutoTurnOnVM-StopActionSaveVMP2VConversionVMMmakesconsolidatingoldserversabreezewithasimplewizardforconvertingphysicalservers(alsoknownasPhysicaltoVirtual(P2V)conversion).
Inthissection,wewillshowyouacoupleofexamplesofcreatingavirtualmachinefromagivencomputersystem.
Listing8.
3hasthePowerShellcodeforanonlineP2V.
Listing8.
3:Convertingaphysicalservertoavirtualmachinewithoutanydowntime#GettheconnectiontotheVMMserverGet-VMMServer-ComputerName"localhost"#Gettheadministrativecredentialsforaccessingthesource#machine(thishastobedomaincredentials)$PSCredential=Get-Credential#GetthetargethostforthisVirtualMachine$VMHost=Get-VMHost-ComputerName"localhost"#InitiatetheasynchronousP2VoperationNew-P2V-SourceComputerName"localhost"-VMHost$VMHost-Name"resultVMName"-Path$VMHost.
VMPaths[0]-MemoryMB1024-Credential$PSCredential-RunAsynchronouslyToinitiateanofineconversionofaWindowsServer2000computer,ortoforcetheofineconversionofaWindowsServer2008computer,youneedtousethe-OfflineagoftheNew-P2Vcmdlet.
Listing8.
4hasthePowerShellcodeforanofineP2V.
Listing8.
4:Ofineconversionofaphysicalservertoavirtualmachine#GettheconnectiontotheVMMserverGet-VMMServer-ComputerName"localhost"#Gettheadministrativecredentialsforaccessingthe#sourcemachine(thishastobedomaincredentials)$PSCredential=Get-CredentialWINDOWSPOWERSHELLEXAMPLES351#GetthetargethostforthisVirtualMachine$VMHost=Get-VMHost-ComputerName"localhost"#Createanewmachineconfigurationforthephysicalsource#computer.
Thistriggersthehardwarescouttoretrievethedata#fromthesourcecomputer.
New-MachineConfig-SourceComputerName"sourcemachine.
vmmdomain.
com"-Credential$PSCredential$MachineConfig=Get-MachineConfig|where{$_.
Name-eq"sourcemachine.
vmmdomain.
com"}#InitiatetheasynchronousofflineP2Voperation,usingastatic#IPAddressfortheconversion#Ifapatchfileordriverismissing,downloadtherequired#patchesordriverfilestothePatchImportdirectoryonthe#VMMserver(thedefaultpathis:\ProgramFiles#\MicrosoftSystemCenterVirtualMachineManager2008\#PatchImport),andextractthefilesbyusingthe#Add-Patchcmdlet.
New-P2V-Credential$PSCredential-VMHost$VMHost-Path$VMHost.
VMPaths[0]-Owner"vmmdomain\administrator"-Trigger-Name"resultVMName"-MachineConfig$MachineConfig-Offline-Shutdown-OfflineIPAddress"192.
168.
100.
23"-OfflineNICMacAddress"00:11:22:33:44:55"-OfflineDefaultGateway"192.
168.
100.
1"-OfflineSubnetMask"255.
255.
255.
0"-CPUCount1-MemoryMB1024-RunAsSystem-StartActionNeverAutoTurnOnVM-UseHardwareAssistedVirtualization$false-StopActionSaveVM-StartVM-RunAsynchronouslyVirtualMachineMigrationsWhenyou'remigratingavirtualmachinethroughVirtualMachineManager,thetransfertype(orspeed)forthemigrationisdeterminedduringIntelligentPlacementanditisbaseduponthepropertiesandcapabilitiesofthesourcevirtualmachineandthedestinationhostalongwiththeconnectivitybetweenthem.
InListing8.
5,weattempttomigrateavirtualmachinewhileenforcingarequirementthatonlySANorclustermigrationsareeligible.
Thisputsarequire-mentonthescripttonotonlycheckforgoodhostratingsbutalsotoensurethatthetransfercanbeaccomplishedquicklyusingaSANorafailovercluster.
Listing8.
5:MigratingavirtualmachineusingclusterorSANandtrackingthemigrationprogress#GetaconnectiontotheVMMserver$c=Get-VMMServer"localhost"352CHAPTER8AUTOMATIONUSINGPOWERSHELL#GettheVMtomigrate$VM=Get-VM"virtualmachine1"#Getallthehosts$AllHosts=Get-VMHost#TheIsMigrationflagallowsthecurrenthostoftheVM#tobeconsideredasthemigrationtarget$hostrating=Get-VMHostRating-VMHost$AllHosts-VM$VM-IsMigration#Orderthehostratings$orderedrating=$hostrating|sort-objectrating-descendingWrite-Output$orderedrating#NowsearchforthetopratedhostthatcandoaClusteroraSANmigration#Allothermigrationoptionsarenotconsideredhere$targethost=$nullforeach($ratingin$orderedrating){if($rating.
Rating-gt0){switch($rating.
TransferType){#Theseoptionsarelistedinorderofdecreasingtransferspeed"Live"{Write-Output"$rating.
NamehasatransfertypeofLive"$targethost=$rating.
Namebreak}"Cluster"{Write-Output"$rating.
NamehasatransfertypeofCluster"$targethost=$rating.
Namebreak}"San"{Write-Output"$rating.
NamehasatransfertypeofSAN"$targethost=$rating.
Namebreak}"Network"{Write-Output"$rating.
NamehasatransfertypeofNetwork"}defaultWINDOWSPOWERSHELLEXAMPLES353{Write-Output"$rating.
NamehasaninvalidTransferType"}}}}if($targethost-eq$null){Write-Warning"WewerenotabletofindasuitabledestinationhostforthisVMwithafasttransfer(SANorCluster)"break}#MigratetheVMtothetargethost$VMHost=Get-VMHost-ComputerName$targethost$resultvm=Move-VM-VM$VM-vmhost$VMHost-Path$VMHost.
VMPaths[0]-RunAsynchronously#GettheVMMJobthatwaslaunchedforthismigration$job=$resultvm.
MostRecentTask#IteratetheloopuntiltheJobisfinishedwhilereportingprogresswhile($job.
Status-eq"Running"){$progress=$job.
ProgressWrite-Progress$VMProgress-PercentComplete$job.
ProgressValue-ID1Start-Sleep3}#TheVMMjobisnowfinished(eitherwithafailedoracompletedstatus)$status=$job.
StatusWrite-Warning"Migrationof$VMtohost$VMHostfinishedwithastatusof:$status"$error=$job.
ErrorInfo|selectDisplayableErrorCode,Problem,RecommendedActionCLIWrite-Warning$errorInsomecases,itisbenecialtoforceaLANmigrationevenwhenafastermigrationoptionisavailable.
TheonlychangefromthecodeinListing8.
5wouldbeasmallchangeintheMove-VMcmdlettoaddtheUseLANoptionasindicatedhere.
#Usethe-UseLANoptiontoforceaNetworktransferoftheVirtualMachine$resultvm=Move-VM-VM$VM-vmhost$VMHost-Path$VMHost.
VMPaths[0]-RunAsynchronously-UseLAN354CHAPTER8AUTOMATIONUSINGPOWERSHELLProvisioningMultipleVirtualMachinesVirtualmachinesareusuallyprovisionedondemandbasedoncustomerrequirements.
How-ever,therearecaseswherehavingmanyvirtualmachinesavailableforimmediateuseisarequirement.
SuchscenariosmightincludehosteddesktopsallocatingvirtualmachinesfromapoolofVMsorallocatingVMstoanenterpriseapplicationbasedonload.
InthePowerShellscriptinListing8.
6,wereadtheinputfromatextleandcreatevirtualmachinesinblocksofveatatime(thethrottlingrateiscustomizable).
ThisallowsustocustomizeandrepeattheautomatedprovisioningprocessbyupdatingatextleratherthanhavingtoadjustaPower-Shellscript.
Listing8.
6:PowerShellscriptforcreatingmultipleVMsbasedonaninputle#getthecommandlineargumentspassedtothisscript$length=$args.
length$expectedArgsLength=2#ThescripttakesasinputthecustomizationfilepathandtheVMMservername$usage="Usage:ScriptName.
ps1"if($length-ne$expectedArgsLength){write-warning$usage;break}#TheArrayListtousefortrackingnew-vmcreations$arraylist=New-ObjectSystem.
Collections.
ArrayList$arraylist.
Clear()#ThemaxnumberofconcurrentVMcreations(throttlingrate)$MaxCreations=5#GetaconnectiontotheVMMserver$servername=$args[1]get-vmmserver-ComputerName$servername#nowopenthecustomizationfiletoreaditsinput$customFile=$args[0]$content=get-content$customFileforeach($valuesin$content){#$valuescontainsonelineofinput.
EachlinerepresentsaVM#nowsplittheCSVinputline$newvalues=$values|%{$_.
split(",")}#Performatesttoensurethepropernumberofparametersexistif($newvalues.
length-ne14)WINDOWSPOWERSHELLEXAMPLES355{write-warning"Thepropernumberofparametersdoesnotexistfor$values";break}#gettheinputvariablesfromthefileandintothespecificvariables$vmname=$newvalues[0]#Thevirtualmachinename$computername=$newvalues[1]#TheguestOScomputername$memory=$newvalues[2]#TheamountofRAMtoallocatetotheVM$OSSKU=$newvalues[3]#TheOSname(VMMhasthesealreadydefined)$ProductID=$newvalues[4]#TheWindowsProductID$description=$newvalues[5]#AdescriptionfortheVM$vmpath=$newvalues[6]#ThepathwheretocreatethisVM$vnetworkname=$newvalues[7]#TheVirtualNetworkName$hostname=$newvalues[8]#ThenameofthehosttoplacethisVMon$cpuvalue=$newvalues[9]#TheCPUName(VMMhasthesealreadydefined)$cpucount=$newvalues[10]#ThenumberofCPUs$owner=$newvalues[11]#TheowneroftheVM$adminpwd=$newvalues[12]#TheguestOSadministratorpassword$templatename=$newvalues[13]#ThetemplatenamefromwhichtocreatethisVM#CreatetheJobGroupIDandthehardwareprofilename$jobguid=[guid]::NewGuid().
ToString()$profilename="Profile"+$jobguid#createtheVMbasedonthesettingsinthefile-thiswillhappenasynchronouslySet-VirtualFloppyDrive-RunAsynchronously-VMMServer$servername-NoMedia-JobGroup$jobguidNew-VirtualNetworkAdapter-VMMServer$servername-JobGroup$jobguid-PhysicalAddressTypeDynamic-VirtualNetwork$vnetworkname-VLanEnabled$falseNew-VirtualDVDDrive-VMMServer$servername-JobGroup$jobguid-Bus1-LUN0$CPUType=Get-CPUType-VMMServer$servername|where{$_.
Name-eq$cpuvalue}New-HardwareProfile-VMMServer$servername-Owner$owner-CPUType$CPUType-Name$profilename-Description"ProfileusedtocreateaVM/Template"-CPUCount$cpucount-MemoryMB$memory-ExpectedCPUUtilization20-DiskIO0-NetworkUtilization10-RelativeWeight100-HighlyAvailable$false-NumLock$false-BootOrder"CD","IdeHardDrive","PxeBoot","Floppy"-LimitCPUFunctionality$false-JobGroup$jobguid$Template=Get-Template-VMMServer$servername|where{$_.
Name-eq$templatename}$VMHost=Get-VMHost-VMMServer$servername|where{$_.
Name-eq$hostname}$HardwareProfile=Get-HardwareProfile-VMMServerlocalhost|356CHAPTER8AUTOMATIONUSINGPOWERSHELLwhere{$_.
Name-eq$profilename}$OperatingSystem=Get-OperatingSystem-VMMServerlocalhost|where{$_.
Name-eq$OSSKU}#Beforewestartthenew-vmcreationweneedtocheck#ifwereachedthemaximumnumberofconcurrentcreationswhile($arraylist.
Count-eq$MaxCreations){$toremove=$nullforeach($jobidin$arraylist){#getthecurrentstatusofthejob$tempjobid=[string]::join("",$jobid.
Keys)$tempjob=Get-Job-ID$tempjobid;if($tempjob.
Status-ne"Running"){#Thisjobcompleted,soremoveitfromthetrackinglistsothatnewVMscanbecreatedWrite-Output"Job$tempjobidfinishedrunning"$toremove=$jobidbreak}}if($toremove-ne$null){$arraylist.
Remove($jobid)}Start-Sleep2}#ifwereachedhere,itissafetocreatethenewVM$resultvm=New-VM-Template$Template-Name$vmname-Description$description-VMHost$VMHost-Path$vmpath-JobGroup$jobguid-Owner$owner-HardwareProfile$HardwareProfile-ComputerName$computername-FullName""-OrgName""-ProductKey$ProductID-TimeZone4-JoinWorkgroup"WORKGROUP"-OperatingSystem$OperatingSystem-RunAsSystem-StartActionNeverAutoTurnOnVM-UseHardwareAssistedVirtualization$false-StopActionSaveVM-RunAsynchronously#Nowstarttrackingthisnew-vminstanceif($resultvm-ne$null){#GettheVMMJobthatwaslaunchedforthismigrationWINDOWSPOWERSHELLEXAMPLES357$job=$resultvm.
MostRecentTask$arraylist.
Add(@{$job.
ID=$job})}}write-output"DonecreatingAllVMs!
"ThefollowingcodecontainsasamplelinefromaninputtextlethatcanbeusedinthescriptinListing8.
6.
ThislinecontainsthevaluesforthedifferentvirtualmachinepropertiesthatareneededbythePowerShellscript.
Thesevaluesneedtobespeciedinorder,andtheirdescriptionsareasfollows:1.
Thevirtualmachinename2.
TheguestOScomputername3.
TheamountofRAMormemorytoallocatetotheVM4.
TheOSname(VMMhasthesealreadydened)5.
TheWindowsproductID6.
AdescriptionfortheVM7.
ThepathdescribingwheretocreatethisVM8.
Thevirtualnetworkname9.
ThenameofthehostonwhichtoplacethisVM10.
TheCPUname(VMMhasthesealreadydened.
)11.
ThenumberofCPUs12.
TheowneroftheVM13.
TheguestOSadministratorpassword14.
ThenameofthetemplatefromwhichtocreatethisVMvmname1,vmname1ComputerName,1024,64-biteditionofWindowsServer2008Enterprise,55555-55555-55555-55555-55555,scriptedVM,D:\ProgramData\Microsoft\Windows\Hyper-V,BroadcomNetXtreme57xxGigabitController-VirtualNetwork,hypervhost1.
vmmdomain.
com,2.
40GHzXeon,1,vmmdomain\administrator,password,MyTemplateAutomatingtheAdditionofManagedHostsAddingavirtualmachinehosttoVMMrequiresadministrativecredentialsforthephysicalcomputer.
Therequirementofcredentialsmakesithardtoautomateanytasksthatneedtorununattendedwithoutsacricingthesecurityofyourcredentials.
SincethecredentialsarerequiredparameterstotheVMMcmdletsinthescriptandstoringthemincleartextmight358CHAPTER8AUTOMATIONUSINGPOWERSHELLcompromisesecurity,youcansaveyourcredentialstoaleforlateruse.
SeethefollowingPowerShellcmdletsforanexample:#First,callGet-CredentialtostoreyourcredentialstoaPowerShellvariable$PSCredential=Get-Credential#Nowconstructthefilepathofthefilethatwillstorethecredentials$SecureFilePath=$PSCredential.
UserName+".
cred"$SecureFilePath=$SecureFilePath.
Replace(#Storethecredentialstothisfile$PSCredential.
Password|ConvertFrom-SecureString|Set-Content$SecureFilePathWhenitistimetoexecutetheautomatedtask,youcanretrievethislefromthesameloca-tionandaddahosttoVMM.
Inthefollowingcodesnippet,wearelookingtoaddallHyper-Vhostsintheenvironment:#Getthepasswordfromthefilethatweusedearliertostoreitin$Password=Get-Content$SecureFilePath|ConvertTo-SecureString#CreateanewPsCredentialobjectforouradministrator#usingthestoredpassword$PSCredential_Out=New-ObjectSystem.
Management.
Automation.
PsCredential("vmmdomain\administrator",$Password)#NowdiscoveralltheHyper-VhostsinthedomainwhosenamestartswithHyperV$Computers=Discover-Computer-ComputerNameFilter"HyperV"-Domain"vmmdomain.
com"-FindHyperVHosts-ExcludeVMMHost|selectName#Theoutputofthediscover-computercmdletcannowbeusedto#addthesehoststoVMMforeach($computerin$Computers){#Insteadofpromptingforcredentials,$PSCredential_Outcontainsthevalues#requiredbyVMMtoaddanewhostAdd-VMHost-Credential$PSCredential_Out-ComputerName$computer}WorkingwithMACAddressesVirtualMachineManagermanagesastaticrangeofMACaddressesthatcanbeusedwhenattachingavirtualnetworkdevicetoaVirtualMachine.
MACaddressesthatareconsumedfromthisstaticrangecanneverbereused,inthesamewaytheMACaddressesonphysicalmachinesareallunique.
ToconguretheMACaddressrange,clickontheadministrationviewoftheVMMAdministratorConsoleandselecttheNetworkingoption.
Figure8.
14showsasampleMACaddressrangeforaVMMdeployment.
WINDOWSPOWERSHELLEXAMPLES359Figure8.
14GlobalStaticMACAddressRangedialogboxListing8.
7showshowtogetthenextavailableMACaddressfromthisrangeandhowtocommittheselection.
OncetheMACaddressiscommitted,itwillneverbeusedagainbyVMM.
Listing8.
7:PowerShellscripttoretrievethenextavailableMACaddress#First,invoketheNew-PhysicalAddresscmdlettoviewthenext#availableMACaddressintherange#Outputwillbesomethinglikethis:00:1D:D8:B7:1C:00New-PhysicalAddress#ifyouexecutetheNew-PhysicalAddressmultipletimes,the#outputwillnotchangefrom00:1D:D8:B7:1C:00New-PhysicalAddress#Now,let'ssavethisMACaddressandcommitthechangeinVMM$MacAddress=New-PhysicalAddress-Commit#PrinttheMACaddresswejustcommitted(shouldbe00:1D:D8:B7:1C:00)$MacAddress#ShowthatthenextinvocationofNew-PhysicalAddresswill#returnanewMACAddressfromtherange.
(00:1D:D8:B7:1C:01)New-PhysicalAddress#OnceyouhaveaMACaddress,youcaninvoketheSet-VirtualNetworkAdapter#cmdlettosettheMACAddress#First,let'sgetthevirtualnetworkadapterforourVirtualMachine1$vnic=get-virtualnetworkadapter-vm""360CHAPTER8AUTOMATIONUSINGPOWERSHELL#NowsetthepropertiesoftheadaptertoincludethisstaticMACAddress$vnic|Set-virtualnetworkadapter-PhysicaladdresstypeStatic-PhysicalAddress$MacAddressEvacuatingaHostforMaintenanceItissometimesnecessarytoservicethephysicalcomputerrunningthevirtualizationsoftware,resultinginseveralhoursofdowntime.
Wewillshowyouascriptthatyoucanusetoevac-uateahostfromallofitsvirtualmachinesinsteadofthevirtualmachinesbeinginactiveaswell.
MakesureyoumonitortheprogressoftheVMMjobstoensurethatallvirtualmachineshavesuccessfullymigratedtoadifferenthost.
Listing8.
8containsthecodeforasynchronouslymovingalltheVMsfromahost.
VMM2008R2alsointroducedanewfeaturecalledmaintenancemode.
AhostmanagedbyVMMcanbeplacedintomaintenancemodeifyouwanttoperformmaintenancetasksonthephysicalhost(e.
g.
,replacehardwareorinstallsecurityupdatesthatmightrequireaserverreboot).
Onceahostisinmaintenancemode,VMMwillnolongerallowthathosttobethetar-gethostforanewvirtualmachine.
Inaddition,ahostthatisinmaintenancemodeisexcludedfromhostratingscalculationsduringvirtualmachineplacement.
Whenmaintenancemodeisinitiatedonahost,allrunningvirtualmachinesareputintoasavedstate.
Ifthehostispartofacluster,thentheuserispresentedwiththeoptiontoeitherlivemigrateallitsvirtualmachinestoanotherhostortosavethestateofallvirtualmachinesonthathost.
Livemigrationisanoptiononlyifthehostclusteriscapableoflivemigration.
ThisbehaviorisalittlebitdifferentforVMwarehosts.
OnceaVMwareESXhostisputintomaintenancemodeinVMM,VMMwillsendan''Entermaintenancemode''requesttoVMwareVirtualCenter.
ThebehavioroftheVMsonthathostisdeterminedbasedonthecongurationofthemaintenancemodefeatureinVirtualCenter.
Whenmaintenancemodeisstoppedonahost,VMMwillallowthathosttobethetargethostofmigrationsandthathostwillstartreceivingastarratinginplacementcalculations.
However,noVMsarerestartedonthathost,andtheVMsthatweremigratedawayfromthathostarenotplacedbackautomatically.
Whenyou'reusingthemaintenancemodefeatureofVMM2008R2,theDisable-VMHostcmdletplacesavirtualmachinehostintomaintenancemodewhileEnable-VMHostremovesahostfrommaintenancemode.
Listing8.
8:PowerShellscripttoasynchronouslymovealltheVMsfromagivenhost#getthecommandlineargumentspassedtothisscript$argslength=$args.
length$expectedArgsLength=2#ThescripttakesasinputtheVMMservernameand#theFQDNofthehosttoevacuate$usage="Usage:ScriptName.
ps1"if($argslength-ne$expectedArgsLength){write-warning$usage;break}WINDOWSPOWERSHELLEXAMPLES361#helperfunctiontomoveaVMtothehostwiththehigheststarrating#ThisfunctioncouldbeeasilymodifiedtoonlymoveVMswithinaSANoraclusterfunctionMoveVM($vmobj,$hostobj){$hostrating=get-vmhostrating-vmhost$hostobj-vm$vmobj$orderedrating=$hostrating|sort-objectrating-descendingWrite-Output$orderedrating$targethost=$nullif($orderedrating-is[Array]){if($orderedrating[0].
Rating-ne0){$targethost=$orderedrating[0].
VMhost}}else{if($orderedrating.
Rating-ne0){$targethost=$orderedrating.
VMHost}}if($targethost-ne$null){write-warning"MovingVM$vmobjtohost$targethost"$resultvm=move-vm-VM$vmobj-vmhost$targethost-Path$targethost.
VMPaths[0]-RunAsynchronously}else{Write-Warning"ThereisnosuitablehostforthisVM$vmobjanditwillnotbemigrated!
"}}#getaconnectiontotheVMMserver$vmmserver=$args[0]$c=get-vmmserver-ComputerName$vmmserver#NowcallGet-VMtocachealltheVMsinPowershell$vms=Get-VM#Getthehostcomputerandallhosts$hostname=$args[1]$VMHost=Get-VMHost-ComputerName$hostname$AllHosts=Get-VMHost362CHAPTER8AUTOMATIONUSINGPOWERSHELL#NowsetthishosttomaintenancemodetopreventVMsfrom#beingdeployedhere$VMHost|Set-VMHost-MaintenanceHost$true#EnumerateallVMsonthishostandmovethemasynchronouslyforeach($VMin$VMHost.
VMs){MoveVM$VM$AllHosts}UtilizingRapidProvisioningVMM2008R2introducedanewfeaturecalledRapidProvisioning.
Thisfeaturewasimple-mentedinresponsetocustomerdemandtoimprovethetimerequiredtocreatevirtualmachines.
InVMM2008,theonlywaytocreateanddeployanewvirtualmachinewasbyutilizingatemplate,anothervirtualmachine,oraVHDfromtheVMMlibrary.
Duringthenewvirtualmachinecreationprocess,VMMcopiedalltherequiredVHDsoverthenetworkusingtheBITSprotocol.
DependingonthesizeofVHDandtheavailablebandwidth,thisoperationcouldtakeseveralminutestocomplete.
SeveralcustomershavesophisticatedSANtechnologiesthatenablethemtocloneaLUNthatcontainstheVHDandpresentittothehost.
However,customersstillwanttoleveragetheVMMtemplatecapabilitieswithoperatingsystem(OS)customization.
RapidProvisioningallowsyoutotakeadvantageofyourfastSANinfrastructuretomove(orcopy)theactualVHDlestothehostbuttiethatbacktoVMM'srichtemplatecustomizationprocess.
WithRapidProvisioning,youcannowcreateatemplatethatincludestheOScongurationandreferencesa''dummy''blankVHD.
TheblankVHDwillnotbeusedandwillbereplacedthroughtheMove-VirtualHardDiskcmdlet.
ThiscmdletwillletVMMknowthatitshouldnotbeusingtheVHDthatisreferencedinthetemplate.
Instead,VMMshoulduseaVHDthatresideslocallyonthehostcomputer.
ToindicatetoVMMthatRapidProvisioningneedstobeused,theNew-VMcmdlettakesanewswitchcalledUseLocalVirtualHardDisk.
RapidProvisioningisonlyavail-ablethroughWindowsPowerShellcmdlets.
Listing8.
9showsanexamplecreationofavirtualmachinebyutilizingRapidProvisioning.
Inthisexample,C:\Win2k8_Base_OS_Sysprep.
vhdhastolocallyexistonthehostcomputerbeforetheNew-VMcmdletisinvoked.
Listing8.
9:CreatinganewvirtualmachineusingRapidProvisioning#StartbyspecifyingthefilelocationfortheVHDthatwill#beusedbytheVirtualMachine$VHDName="c:\Win2k8_Base_OS_Sysprep.
vhd"#Specifyothervariablesfornew-vmcmdlet$vmname="vm1"$hostname="host.
contoso.
com"WINDOWSPOWERSHELLEXAMPLES363#Getaninstanceofthehostthatwillbethetarget#fortheVirtualMachine$vmhost=get-vmhost$hostname#CreatethejobgroupIDfornew-vmfromtemplate$JobGuid=[System.
Guid]::NewGuid().
ToString()#SpecifythelocallocationfortheVHD#Thatwillreplacethe"dummy"VHDthatexistsinthetemplate#VMMexpectsthat$VHDNamealreadyexistsonthehostcomputer#whenthenew-vmcmdletiscalled.
Move-VirtualHardDisk-Bus0-LUN0-IDE-Path$VHDName-JobGroup$JobGuid#GettheinstanceofthetemplatethatwillbeusedforOSConfiguration$template=Get-Template|where{$_.
Name-eq"VMMTemplate"}#GetthecurrentusernametobepassedastheVirtualMachineowner$callerUsername=whoami#Createthenew-vmfromtemplateandspecifytheRapid#Provisioningflag(-uselocalvirtualharddisks)New-VM-Template$template-Name$vmname-Description"aVirtualMachinecreatedwithRP"-Owner$callerUsername-VMHost$vmhost-UseLocalVirtualHardDisks-Path$vmhost.
VMPaths[0]-RunAsynchronously-JobGroup$JobGuid|Out-NullEventhoughVirtualMachineManagerdoesnotprovideUIsupportforcreatingavirtualmachineusingdifferencingVHDdisks,thiscanbeaccomplishedusingRapidProvisioning.
UsingthepublicHyper-VWMIinterface,youcancreateadifferencingdiskforthec:\Win2k8_Base_OS_Sysprep.
vhdVHDleusedinListing8.
9.
Then,whentheMove-VirtualHardDiskcmdletisexecuted,youcanpassthefullpathtothechildVHD.
ThedifferencingdiskwillthenbeusedasthetargetVHDforthenewvirtualmachinecreation.
SuchaprocesswouldmakeiteasyforcustomerstocopyasinglebasediskwiththeoperatingsystemonahostandthenusetheRapidProvisioningfeaturetocreatemultiplevirtualmachinesusingdifferencingdisksoffthatsameparentVHD.
ThefollowingcodesnippetshowsyouapartialscriptthatcreatesadifferencingdiskfromthebaseVHD.
ThenitsuppliesthenewVHDlepathtoVMMforRapidProvisioning.
ThefollowingcodecanbeusedwithinListing8.
9tocreateanewvirtualmachineusingdifferencingdisksandRapidProvisioning:#GettheImageManagementServiceWMIinstanceforthehostcomputer$VHDService=get-wmiobject-class"Msvm_ImageManagementService"-namespace"root\virtualization"-computername$hostname#Createadifferencingdiskfromthebasedisk$DiffVHDName="c:\Win2k8_Base_OS_Sysprep_child.
vhd"$Result=$VHDService.
CreateDifferencingVirtualHardDisk($DiffVHDName,$VHDName)364CHAPTER8AUTOMATIONUSINGPOWERSHELL#WaituntiltheHyper-Vdifferencingdiskcreationiscomplete#andthenpassDiffVHDNametotheMove-VirtualHardDiskcmdlet#ThiswillnotifyVMMtousethedifferencingdiskforNew-VM#insteadofthebasedisk$VHDNameMove-VirtualHardDisk-Bus0-LUN0-IDE-Path$DiffVHDName-JobGroup$JobGuidInadditiontothenewUseLocalVirtualHardDisks,VMM2008R2hasaddedonemorenewswitchforNew-VMcalledSkipInstallVirtualizationGuestServices.
ThisswitchnotiesVMMtoskiptheinstallationoftheIntegrationComponents(ICs)(alsoknownasVirtualGuestServices)aspartoftheNew-VMcmdlets,decreasingtheamountoftimerequiredforNew-VMtocomplete.
ThisswitchshouldbeusedonlyifyouarealreadycertainthatyourtemplateeithercontainstheICsorcontainsanoperatingsystemthathasbuilt-inintegrationcompo-nents.
ItisimportantthatyouensurethatallyourVMshavetheintegrationcomponentscor-rectlyinstalledtotakefulladvantageofvirtualizationandvirtualizationmanagement.
TheSkipInstallVirtualizationGuestServiceswilltakeeffectonlyinthefollowingthreeNew-VMscenarios:NewvirtualmachinefromVHDNewvirtualmachineutilizinganexistingvirtualmachineNewvirtualmachinefromatemplatethatdoesnothaveanOScongurationspeciedThefollowingcodeshowsanexampleinvocationoftheNew-VMcmdletthatutilizesthisnewswitch.
ThisnewswitchcanalsobeusedalongwiththeUseLocalVirtualHardDisksswitchtofurtherspeeduptheNew-VMprocess.
Here'sthecode:#Specifyvariablesneededforthenew-vmcmdlet$vmname="vm2"$hostname="host.
contoso.
com"#Getaninstanceofthehostthatwillbethetarget#fortheVirtualMachine$vmhost=get-vmhost$hostname#CreatethejobgroupIDfornew-vmfromtemplate$JobGuid=[System.
Guid]::NewGuid().
ToString()#GettheinstanceofthetemplatethatwillbeusedforOSConfiguration$template=Get-Template|where{$_.
Name-eq"VMMTemplate"}#GetthecurrentusernametobepassedastheVirtualMachineowner$callerUsername=whoami#Createthenew-vmfromtemplateandspecifythe#SkipInstallVirtualizationGuestServicesswitchtoskip#theInstallVMcomponentsstepoftheNew-VMcmdletNew-VM-Template$template-Name$vmname-Description"aVirtualMachinecreatedwithRP"-Owner$callerUsernameWINDOWSPOWERSHELLEXAMPLES365-VMHost$vmhost-SkipInstallVirtualizationGuestServices-Path$vmhost.
VMPaths[0]-RunAsynchronously-JobGroup$JobGuid|Out-NullSpecifyingCPUSettingsTheVirtualMachineManagerAdministratorConsoleonlyexposestheVirtualMachinePrioritysettingaspartofthevirtualmachineproperties.
ThepriorityofaVM,whichdecideshowtoallocateCPUresourcesonthehostforthisVM,canbespeciedintheHardwareCongurationtab,asshowninFigure8.
15.
VMMexposestwomoreCPUpropertiesforavirtualmachinethroughWindowsPowerShellonlyandtheSet-VMcmdlet:CPUMaxSpeciesthehighestpercentageofthetotalresourcesofasingleCPUonthehostthatcanbeusedbyaspecicvirtualmachineatanygiventime.
CPUReserveSpeciestheminimumpercentageoftheresourcesofasingleCPUonthehosttoallocatetoavirtualmachine.
ThepercentageofCPUcapacitythatisavailabletothevirtualmachineisneverlessthanthispercentage.
AthirdPowerShellproperty,calledRelativeWeight,isthesameastheVMPriorityprop-ertyseeninFigure8.
15.
UsethiscommandtocreateanewhardwareprolewiththethreeCPUpropertiessetatdifferentlevels.
Figure8.
15CPUpriorityforavirtualmachine366CHAPTER8AUTOMATIONUSINGPOWERSHELLThefollowingcodeshowsanexamplecreationofavirtualmachinewiththeCPUproperties:#Gettheinstanceofahost$vmhost=get-vmhost"host.
contoso.
com"#GettheinstanceofaVHDthatwillbeusedduringNew-VM$vhd=(Get-VirtualHardDisk)[0]#CreateanewhardwareprofilewiththeCPUsettingsset$hwProfile=New-HardwareProfile-Name"cpuHWProfile"-description""-CPUMax70-CPUReserve50-RelativeWeight80#CreatethenewVirtualMachinewiththehardwareprofilespecifiedNew-VM-Name"cpuVM"-VirtualHardDisk$vhd-VMHost$vmhost-HardwareProfile$hwProfile-Path$vmhost.
VMPaths[0]#ShowthatthenewVirtualMachinecreatedhasthespecifiedCPUsettingsGet-VM-Name"cpuVM"|SelectName,Hostname,CPUMax,CPUReserve,RelativeWeightClusteringCmdletSwitchesVMM2008R2providessupportforthenewWindowsServer2008R2Hyper-Vfeatures,includ-ingLiveMigrationinafailoverclusterenvironment.
FromtheVMMAdministratorConsole,ifLiveMigrationisavailableforavirtualmachine,thenthatistheonlyoptionofferedtoanadministratorformigratingthevirtualmachinetoanothernodeinthecluster.
IfyouwanttoforcethetransfertypeofthevirtualmachinetobeQuickMigration(QuickMigrationsavesthestateofavirtualmachinepriortochangingitsownershiptoanothernodeinthecluster)evenifHyper-VLiveMigrationisavailable,usetheUseClusterswitchwiththiscommand:Move-VM-VM$myVM-vmhost$VMHost-Path$VMHost.
VMPaths[0]-UseClusterHyper-VLiveMigrationallowsonlyoneclusternodetoparticipateinalivemigrationatanypointintime.
VMMimplementedaqueuetotrackactivelivemigrationsandensurethatalluser-executedlivemigrationscompleteinorder.
IfyouwouldliketheMove-VMcmdlettofailifaHyper-Vlivemigrationisinprogressandyourlivemigrationcannotstartimmediately,usetheBlockLMIfHostBusyswitchwiththiscommand(thisswitchwillnotutilizetheVMMLiveMigrationqueue):Move-VM-VM$myVM-vmhost$VMHost-Path$VMHost.
VMPaths[0]-BlockLMIfHostBusyMonitoringandReportingCreatingautomatedtasksthatchecksthehealthofyoursystemandemailstheadministratoroncriticalerrorscanbeaccomplishedveryeasilywithafewcmdlets.
Inthissection,wewillshowyouafewcmdletsthatcanproveusefulinassessingtheoverallhealthofyoursystem.
Ifyouwouldliketobundlethesescriptsintoanautomatedtaskandenableemailnotication,youcanlookintotheSMTPemailingpropertiesoftheclassSystem.
Net.
Mail.
MailMessage.
WINDOWSPOWERSHELLEXAMPLES367Usethiscommandtogettheoverallstatusofthevirtualmachines'health:Get-VM|SelectName,ID,Status|sort-objectStatusUsethiscommandtogetalistofallvirtualmachinesandtheirhostnames:#VMIDistheuniqueidentifieroftheVMonthevirtualizationplatform(i.
e.
Hyper-V)#IDistheuniqueidentifieroftheVMinVirtualMachineManagerGet-VM|SelectName,ID,HostName,VMIDUsethiscommandtogetalistofthelastjobrunoneachvirtualmachine:Get-VM|SelectName,ID,MostRecentTaskUsethiscommandtogetthehealthinformationofthehosts:Get-VMHost|selectName,OverallState,CommunicationState,VirtualServerState,VirtualServerVersionStateUsethiscommandtogetthehealthinformationofthemanagedphysicalcomputers:Get-VMMManagedComputer|selectName,State,VersionState,UpdatedDateUsethiscommandtocreateareportoftwocustompropertiesofavirtualmachine:#YoucanusetheCustomerPropertiesofaVMtoaddanydatayouwouldliketo#associatewithaVM.
Inthisexample,wechoseCostCenterand#LastUpdatedforthefirsttwocustompropertiesGet-VM|selectName,Status,@{Name='CostCenter';Expression={$_.
CustomProperties[0]}},@{Name='LastUpdated';Expression={$_.
CustomProperties[1]}}UsethiscommandtogetthelistofvirtualizationplatformsinVMM:Get-VMHost|selectName,VirtualizationPlatformDetail|sort-objectVirtualizationPlatformDetail-descendingUsethiscommandtogetthelast10jobsthatwereruninVMM,theirowners,andtheaffectedobjects:$jobs=get-job|sort-objectStartTime-Descending|selectName,ResultName,ResultObjectType,Status,Owner$jobs[0.
.
10]WheninvokingWindowsPowerShellcmdlets,itisusefultobeabletoidentifyifanerroroccurred.
Usethefollowingcommandtoclearanyexistingerrorsintheerrorpipelineandthenusethesameobjecttocheckforerrors:#Clearanyexistingerrorsfromtheerrorpipeline$Error.
Clear()368CHAPTER8AUTOMATIONUSINGPOWERSHELL#Invokeacmdlet.
Asanexample,Iusedget-vmmserver$c=get-vmmserver-ComputerName"localhost"#Checkifanyerrorsoccurredif($Error.
Count-ne0){#Anerroroccurredhere.
Dosomethingaboutitandterminate#thescript}TheBottomLineDescribethemainbenetsthatPowerShelloffersforVMM.
WindowsPowerShellisarelativelynewtechnologythatwasdevelopedbyMicrosoftCorporation.
VirtualMachineManagerutilizedthistechnologyasthescriptingpublicAPIforVMMandasthebackboneoftheAdministratorConsole.
MasterItWhatversionofWindowsPowerShelldoesVMMsupportWhicharetheVMMassembliesneededforprogrammaticallyintegratingwithVMM'scmdletsListthebenetsthatWindowsPowerShellcmdletsofferasapublicAPI.
CreatescheduledPowerShellscripts.
SchedulingPowerShellscriptsallowsanadministratortoperformoperationsduringnonworkhoursandgetreportsontheprogressandtheresultsofthoseoperations.
MasterItHowcanyoucreateascheduledtaskinWindowsListanexamplePowerShellscriptthatchecksifanyhostisinanunhealthystateandneedsanadministratortotakealookatit.
UsetheVMMPowerShellcmdlets.
Understandingtheusage,scope,andassociationofthedifferentVMMcmdletsandPowerShellobjectsallowsanadministratortoeffectivelymanageVMMthroughWindowsPowerShell.
MasterItHowcanyouidentifytheproperparametersandsyntaxfortheAdd-VMHostcmdletHowcanyouaddtheVMMPowerShellsnap-inprogrammaticallytoaPowerShellscriptHowdoestheWindowsPowerShellpipelinework
racknerd怎么样?racknerd美国便宜vps又开启促销模式了,机房优秀,有洛杉矶DC-02、纽约、芝加哥机房可选,最低配置4TB月流量套餐16.55美元/年,此外商家之前推出的最便宜的9.49美元/年套餐也补货上架,同时RackNerd美国AMD VPS套餐最低才14.18美元/年,是全网最便宜的AMD VPS套餐!RackNerd主要经营美国圣何塞、洛杉矶、达拉斯、芝加哥、亚特兰大、新...
EtherNetservers是一家成立于2013年的英国主机商,提供基于OpenVZ和KVM架构的VPS,数据中心包括美国洛杉矶、新泽西和杰克逊维尔,商家支持使用PayPal、支付宝等付款方式,提供 60 天退款保证,这在IDC行业来说很少见,也可见商家对自家产品很有信心。有需要便宜VPS、多IP VPS的朋友可以关注一下。优惠码SUMMER-VPS-15 (终身 15% 的折扣)SUMMER-...
达州创梦网络怎么样,达州创梦网络公司位于四川省达州市,属于四川本地企业,资质齐全,IDC/ISP均有,从创梦网络这边租的服务器均可以备案,属于一手资源,高防机柜、大带宽、高防IP业务,一手整C IP段,四川电信,一手四川托管服务商,成都优化线路,机柜租用、服务器云服务器租用,适合建站做游戏,不须要在套CDN,全国访问快,直连省骨干,大网封UDP,无视UDP攻击,机房集群高达1.2TB,单机可提供1...
parameters add为你推荐
怎么在qq空间里添加背景音乐怎么在QQ空间里插入背景音乐??pwlosera,pw是什么,是不认识的人发的短信。请解释::网站联盟网站联盟的运作流程不兼容vivo手机和软件不兼容怎么办?qq空间装扮qq空间的装扮空间在哪?如何建立一个网站如何建立一个网站?彩信中心联通手机的彩信中心如何设置?qq怎么发邮件用QQ怎样发送文件二层交换机二层交换机是什么意思,三层呢机械键盘轴大家觉得机械键盘什么轴最舒服
双线虚拟主机 服务器租用托管 arvixe inmotionhosting 安云加速器 12306抢票攻略 seovip php探针 tk域名 合肥鹏博士 智能骨干网 卡巴斯基官方免费版 hktv 网游服务器 web服务器安全 爱奇艺会员免费试用 网页提速 太原联通测速 路由跟踪 ebay注册 更多