establishparameters

parameters add  时间:2021-02-19  阅读:()
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

DogYun(300元/月),韩国独立服务器,E5/SSD+NVMe

DogYun(中文名称狗云)新上了一批韩国自动化上架独立服务器,使用月减200元优惠码后仅需每月300元,双E5 CPU,SSD+NVMe高性能硬盘,支持安装Linux或者Windows操作系统,下单自动化上架。这是一家成立于2019年的国人主机商,提供VPS和独立服务器租用等产品,数据中心包括中国香港、美国洛杉矶、日本、韩国、德国、荷兰等。下面分享这款自动化上架韩国独立服务器的配置和优惠码信息。...

稳爱云(26元),香港云服务器 1核 1G 10M带宽

稳爱云(www.wenaiyun.com)是创建于2021年的国人IDC商家,主要目前要出售香港VPS、香港独立服务器、美国高防VPS、美国CERA VPS 等目前在售VPS线路有三网CN2、CN2 GIA,该公司旗下产品均采用KVM虚拟化架构。机房采用业内口碑最好香港沙田机房,稳定,好用,数据安全。线路采用三网(电信,联通,移动)回程电信cn2、cn2 gia优质网络,延迟低,速度快。自行封装的...

PacificRack 端午节再来一款年付$38 VPS主机 2核4GB内存1TB流量

这不端午节和大家一样回家休息几天,也没有照顾网站的更新。今天又出去忙一天没有时间更新,这里简单搜集看看是不是有一些商家促销活动,因为我看到电商平台各种推送活动今天又开始一波,所以说现在的各种促销让人真的很累。比如在前面我们也有看到PacificRack 商家发布过年中活动,这不在端午节(昨天)又发布一款闪购活动,有些朋友姑且较多是端午节活动,刚才有看到活动还在的,如果有需要的朋友可以看看。第一、端...

parameters add为你推荐
网页解密如何查看网页中的密码行业关键词为什么有些行业关键词竟价出价很低有些行业很高网络明星哪个知道这个网络明星叫什么?百度手写百度如何手写:安卓应用平台手机系统应用在哪如何建立一个网站怎样能创建一个网站怎么点亮qq空间图标如何点亮QQ空间图标二层交换机什么是三层交换机?什么是二层叫交换机?有什么区别?分词技术怎么在SEO中学会运用关键词分词技术虚拟机软件下载谁有虚拟机软件的网址要好用的
西安电信测速 韩国电信 鲜果阅读 php空间推荐 免费活动 佛山高防服务器 cn3 申请网页 新世界服务器 根服务器 阿里云手机官网 服务器托管价格 hdsky iptables 大容量存储方案 qq空间排行榜 电脑主机报警 海贼王789 789** 英国伦敦时间 更多