Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

429 e8d01

986 views

Published on

Published in: Education, Technology
  • Be the first to comment

  • Be the first to like this

429 e8d01

  1. 1. PowerShell Basics - 1 PowerShell Basics - 2 VMware PowerCLI 1.5 cardProfiles Wildcards # Get-Help about_Wildcards<InstallDir>profile.ps1 - general Profile file * # all chars, no limit%userprofile%<Documents>WindowsPowerShellprofile.ps1 - PowerShell User profile ? # all chars, one charWithin the Shell [a-j ] # chars a, b ... j, one char [ajz] # chars a, j, z, one charCommands Version 1.0# # for commenting lines boolean by Dennis Zimmer; # for multiple commands, i.e. $i = $true # sets $i true $i = $false # sets $i false icomasoft AG, www.icomasoft.com PowerCLI 1.5 get-process;get-service;get-vmF7 for command history If statements PowerShell Basics - 3cursor up/cursor down # walking through commands history if (condition) {…}Get-History # command history elseif (condition) {…}ESC # clear current line else {…}CTRL + C # abort Command execution if (($i –ge 5) –and ($i –le 7)) {…}clear # clear whole screen User Input Switch, for multiple statements Read-Host [[-prompt] Object] [-asSecureString] [CommonParameters]Variables switch (expression) { $myinput = Read-Host $mypass = read-host „Enter a Password:“ -assecurestringdir variable: # show all variables Value1 {…} Get-Credential [-credential] PSCredential [CommonParameters]$? # last error code Value2 {…} $cred = Get-Credential $aduser = Get-Credential domainaduser$number = 123 default {…} } Script Output[int]$i = 5$string = “abc” $variable # outputs variable content Loops$_ = current object in pipeline $error # list last errors while (expression) {…}$myobject = get-process calc > $NULL 2>&1 # suppress output, i. e. while ($i –le 5) {…}Numbers: [int], [long], [double], [decimal], [float], [single], [byte] connect-viserver vcserver > $NULL 2>&1Strings: [string] , [char] Do Loop (run while $a >= 10 (9 times) “Output of ` $variable: $variable“ # Escape Char ` to output special$var1, $var2 = $var2, $var1 # switch variable content $a=1 characters Do {$a; $a++} “Today´s date: “ + (get-date) # merge Text with Cmd-LetVariable Scope While ($a –lt 10) Out-Host [-paging] [-inputObject psobject] [CommonParameters]$global: i = 5; $script: i = 5;$local: i = 5 (Default); $private: I = 5 (within function) get-datastore | out-host -paging # show all datastores one page at a time at console run until $a >= 10 (10 times) Out-File [-filePath] string [[-encoding] string] [-append] [-width int] [-inputObject psobject] [-force]Arrays $a=1 [-noClobber]$a = 1,2,3 # Array with 3 Elements Do {$a; $a++} get-vm | out-file C: docsprocess.txt # write utput of get-vm overwriting process.txt$a += , $vm.name # adding Array element Until ($a –gt 10) Export-Clixml [-path] string -inputObject psobject [-depth int] [-force] [-encoding string] [-noClob-$a = $a -ne “ “ # Remove empty Array elements For loops ber]$a[2] = $Null # Remove third Array Element for([initializer]; [condition]; [iterator] ) { …} Get-VM | Export-CliXML C: ScriptsTest.xml$a[0] , $a[2] , $a[-1 ] # getting first, third element of array, for($i = 1 ; $i –le 10; $i++) { …} # writes XML file last element of array Export-Csv [-path] string -inputObject psobject [Options]$result = @( ) # initializing $result as empty array Foreach-Object or Foreach or % Get-VM | Export-Csv -path c: vms.csv # stores all VM data within XML file foreach(identifier in Collection) {…} Out-GridView [-InputObject <psobject>] # PowerShell 2 CTP3 & .net Framework 3.5 requiredobject manipulation foreach($vm in get-vm) {stop-vm $vm} # Stop all VMs Get-VM | Out-GridView # Displays a Gridview with the input Objects(get-process calc).Workingset/1kb foreach($host in get-vmhost) {$host.name} - limited to 10 columns(get-process calc).WaitForExit() # Show all Host names Calling external scripts“abc”.ToUpper() get-vm | % {stop-vm $_} # Stop all VMsFunction powershell.exe „. c: script.ps1“ function name ([string]$parameter1, [int]$parameter2, …) {...}Hashtable function listvm([string]$vm) Calling scripts within PowerShell$hash = @{Name1 = “Value1”; Name2 = “Value2”} { .script.ps1 =script usage with variable scope # create Hashtable $vms = Get-VM $vm &script.ps1 = new scope, variables of calling script not valid$hash[”Name1 “, ”Name2“] # read Hashtable return $vms powershell -command “& ‘MyScript.ps1‘ “$hash.Name2 = ”Value2“ # expand Hashtable } # Run PowerShell Script with Windows Scheduler$hash.remove(”Name1 “) # remove Hash Entry $vms = listvm(“VMname“)$hash = @{ } # initializing $hash as empty Hashtable Record SessionsCalculate Piping & Pipeline Start-transcript -path c: transcript0.txt PowerShell allows to process the object output of one CmdLet to be piped into Input of another Stop-transcript+, -, *, / # basic arithmetic Cmdlet # Convert Hashtable to Object - very helpful for$i = $i +5 # increase $i by 5 Get-Cluster “CL1“ | Get-VM | Get-CDDrive custom attribute or adv. config formatting$i += 1 # increase $i by 1 # Shows all CD Drives ofVMs within Cluster CL1 function ConvertTo-Object {$i -= 1 # decrease $i by 1 begin { $object = New-Object Object }$i++ # increase $i by 1 Object Properties process {“abc” + “def” # joining strings to abcdef PowerShell allows to direct access or iterate Object properties and methods directly $_.GetEnumerator() | ForEach-Object { Add-Member -inputObject $object -memberType5%4.5 = 0,5 # modula Get-VM | Get-Member # gets information about object NoteProperty -name $_.Name -value $_.Value } }$abc -like ”a*“ # returns $true if $abc begins with “a” properties and methods end { $object } -notlike (Get-VM VM1 ).Guest.OSFullName # retrieves Guest OS Full name ofVM1 }$array -contains “VM1“ # returns $true if array contains VM1 To suppress confirmation messages append confirm:$false to command $hash1 = @{name=‘cust1 ‚;value=‘123‘}“book“-match“ [iou]“ # regular expression filter CmdLet Info $hash1 | ConvertTo-Object -notmatch-or, -and, -not # or, and or not statement Get-Help [-name] string] [ {-full | -detailed | -examples } # .Net Objects“VM-Name1“ -replace“VM“, “Host“ # Replace String get-help get-vm Returns a VMware Infrastructure .Net view object by specified search criteria. Get-Command [-name] string[] ] $vm = Get-View -ViewType VirtualMachine -Filter @{„Name“ = „XPVM“}Compare get-command get-v* $hostView = (Get-View -ID $vm.Runtime.Host).Summary.Runtime-eq, -ne, - le, -lt, -ge, -gt Get-Command -commandtype CmdLet get*$i –eq 123 # $i equal 123 # show all Get - CmdLets # Get VMotion Info$i –ne 5 # $i not equal 5 Get-Command -PSSnapin VMware.VimAutomation.Core (Get-View (Get-Host ‘ESX1‘ | get-view).ConfigManager.VmotionSystem).SelectVnic(‚vmk0‘)$i --lt 5 # $i less than 5 # show all VI Toolkit CmdLets$i –le 5 # $i less equal 5 # Get Portgroup VLAN ID$i –ge 5 # $i greater equal 5 Get-VM | %{ Write-Host $_.Name `t ($_ | Get-VirtualPortGroup | Select vlanid)}
  2. 2. PowerCLI Installation VMware ESX - 1 VMware ESX - 2InstallWindows PowerShell To list all the VMware Infrastructure Servers (VMHost) on the connected $ns.UpdateDnsConfig($dns) VI Server }Version 1:http://www.microsoft.com/technet/scriptcenter/topics/msh/download.mspx Get-VMHost ESX SNMP Configuration (requires direct ESX Host connection)Version 2 CTP3: Get all Hosts member of a Cluster $hostSNMP = Get-VMHostSNMPhttp://go.microsoft.com/fwlink/?LinkID=131969 Set-VMHostSNMP $hostSNMP -Enabled:$true -ReadOnlyCommunity ‚public‘ Get-Cluster Cluster01 | Get-VmHostBefore installing VMware PowerCLI set lower Security:Set-ExecutionPolicy RemoteSigned To add a new VMHost to inventory (requires connection to vCenter) vSphere Hostprofiles Add-VMHost ESX01 -Location (Get-Datacenter Main) -User root -Password MyPass $p = ( Get-VMHostProfile -Name testProfile )[0]or registry edit: Set-VMHostProfile -Profile $p -Description ”Edited the description?“HKLMSoftwareMicrosoftPowerShell1 ShellIdsExecutionPolicy to RemoteSigned Add host using different VPXAgent Port and Credential Dialog Test-VMHostProfileCompliance -VMHost (Get-VmHost ESX01 )VI Toolkit: Add-VMHost ESX1 -Location (Get-Datacenter myDC) -Port 910 -Credentials (Get-Credential) Get-VMHostProfile -Name ”Profile01” | Remove-VMHostProfile -Confirm:$falsehttp://www.vmware.com/sdk/vitk_win/index.html Apply-VMHostProfile -Entity (Get-VmHost ESX01 ) -Profile $p -Confirm:$falsePowerShell Editor PowerGUI: To remove a VMHost New-VMHostProfile MasterProfile -Description ”Profile from ESXMaster“http://www.powergui.org Get-VMHost ESX01 | Remove-VmHost -ReferenceHost (Get-VmHost ESXMaster) To move a VMHost Export-VMHostProfile -FilePath export.prf -Profile $p -ForceVI Toolkit for Windows Community Extensions:http: //www.codeplex.com/vitoolkitextensions Move-VMHost (Get-VMHost ESX01 ) -Destination (Get-Datacenter MyDatacenter) Change License Server (Thanks to Hugo Peeters, www.peetersonline.nl)Get-VIToolkitVersion [<CommonParameters>] To change the state of a VMHost $SI = Get-View ServiceInstance # get VI Toolkit version Set-VmHost -VmHost ESX01 -State ”Disconnected“ $LicMan = Get-View $SI.Content.LicenseManagerSet-VIToolkitConfiguration -ProxyPolicy NoProxy -Confirm:$false # Disconnect Host $VMHost = Get-VMHost ESX01 # avoid IE proxy Set-VmHost -VmHost (Get-VmHost -Name ”ESX01”) -State ”Maintenance“ $hostref = ($VMHost | Get-View).MoRef $LicServer = „27000@LicenseServer.domain.local“ Community Extensions # Enter Host # new license server Connect Host or Exit Maintenance $licsrc = New-Object VMware.Vim.LicenseServerSource Set-VmHost -VmHost (Get-VmHost -Name ”ESX01”) -State ”Connected“ $licsrc.LicenseServer = $LicServer ESX Advanced Configuration $LicMan.ConfigureLicenseSource($hostref,$licsrc) StorageThe VITK Community Extensions is a PowerShell Module that contains enhanced Get-VMHostAdvancedConfiguration -VMHost (Get-VMHost ESX01 ) -Name scsi*Log*functionality to the official VITK. These extensions are developed by community members. Get-VMHost ESX01 | Set-VmHostAdvancedConfiguration -Name ”Scsi.LogMultiPath“ -Value 1You need PowerShell version 2 (current CTP3) to be able to load the module withadd-module vitoolkitextension.psm1 Read and Configure Host Modules (requires direct ESX connection)Most of the Cmdlets are following the syntax verb-TKEnoun – like Get-TKEVMPath for $module = Get-VMHostModule -Name qla2300_707_vmw.o List Datastoresgetting the Path of the VM by given VMX file. Others are non VMware specific Locate, # Get Infos about QLogic HBAModule Get-Datastore # List all DataStores with defaultParse or cast CmdLets.There is a install.cmd included within the VITKE archive for installing the Toolkit Extension set QLogic HBAModule Option properties Set-VMHostModule -HostModule $module -Options“qlport_down_retry=60“ Get-VMHost ESX01 | Get-Datastore # List all Datastores of ESX Host ESX01and loading it within profile.ps1 Get-Datastore | where {$_.type -eq „NFS“}Some of the Extensions help to: Manage VM StartPolicy of ESX Host # List all NFS DatastoresESX Maintenance Mode Set-TkeVMHostMaintenanceMode Get-VMHost ESX01 | Set-VMHostStartPolicy -Enabled $true Get-VMHost | Get-VMHostStartPolicy Create New Datastores.Net Objects New-Datastore -Nfs -VMHost (Get-VmHost ESX01 ) -Name NFS01 -Path ”/vol/nfs“ -NfsHost Get-VMHost | Get-VMHostStartPolicy | Set-VMHostStartPolicy -StopAction GuestShutDownReturns a VMware Infrastructure .Net view object by specifed search criter nfs.domain.test$vm = Get-View -ViewType VirtualMachine -Filter @{„Name“ = „XPVM“} ESX Host Accounts (requires direct ESX Host connection) New-Datastore -Vmfs -VMHost (Get-VmHost ESX01 ) -Path ”vmhba1:0:4“ -Name LUN01$hostView = (Get-View -ID $vm.Runtime.Host).Summary.Runtime Get-VMHostAccount -userGet-VM | Get-View | Get-Member # Show all .net Properties and Methods New-VMHostAccount -ID user -Password password -UserAccount Delete Datastores of virtual machine objects New-VMHostAccount -Id normalusers -GroupAccount -AssignUsers user Remove-Datastore -Datastore (Get-Datastore -Name NFS01 ) -VMHost ESX01 -Confirm:$false Get-VMHostAccount - Group -ID user | Remove-VMHostAccount -Confirm Change Datastore Friendly Name Connect VI Server Firewall Policy Configuration $fwconf = Get-VMHostFirewallDefaultPolicy -VMHost (Get-VMHost ESX01 ) Set-VMHostFirewallDefaultPolicy -Policy $fwconf -AllowOutGoing $true Get-Datastore -Name ”NFS01” | Set-Datastore -Name oldNFS Storage Pathing $scsilun = Get-ScsiLun -VMHost ESX01 -LunType diskTo use PowerCLI you have to be connected to a VMware ESX oder VM- Get-VMHostFirewallException -VMHost (Get-VMHost -Name ESX01 ) -Enabled $true $scsilun | Set-ScsiLun -CommandsToSwitchPath 100 $sshfw = Get-VMHostFirewallException -Name ”SSH Client“ware VirtualCenter Server. $scsilun | Set-ScsiLun -MultipathPolicy Fixed $sshfw | Set-VMHostFirewallException -Enabled $trueConnect-VIserver [-Server] <String[]> [-Port <Int32>] [-Protocol <String>] [-Credential $scsipath = Get-ScsiLunPath $scsilun<PSCredential>] [-User <String>] [-Password <String>] [-Session <String>] [<CommonParame- Service Configuration (requires direct ESX connection) Set-ScsiLunPath -ScsiLunPath $scsipath -Preferred $true -Active $trueters>] Get-VMHostService -Refresh Rescan or Refresh DatastoresConnect-VIServer -Server 10.23.112.235 -Protocol https -User Administrator -Password pass01 $ntpd = Get-VmHostService -VMHost 192.168.1.10 | ?{$_.key -eq ”ntpd“} Get-VmHostStorage (Get-VmHost ESX01 ) -Refresh$srv = Connect-VIServer 10.23.115.133 -User Admin -Password Pass01 Set-VmHostService -Service $ntpd -Policy „Automatic“ # Refresh DatastoresConnect-VIServer 10.23.115.133 -Session $srv.SessionId Get-VmHostService -VMHost 192.168.1.10 | ?{$_.key -eq ”vmware-vpxa“} | Get-VmHostStorage (Get-VmHost ESX01 ) -RescanAllHbaYou can either connect to one or multiple VMware ESX or VirtualCenter Server. Restart-VMHostService # Rescan SANConnect multiple VirtualCenter Server with current user account: $ntpd | Start-VMHostService Get-VmHostStorage (Get-VmHost ESX01 ) -RescanVmfs$vcs = @() $ntpd | Stop-VMHostService # Rescan VMFS$vcs += Connect-VIServer vc1 .network.test$vcs += Connect-VIServer vc2.network.test NTP Server settings Get-VMHostStorage | select -expandproperty scsilun | fl * Get-VMHostNtpServer ESX01 # Read Storage information$vcs += Connect-VIServer vc3.network.test Task InformationGet All VMs managed by multiple vCenter server Get-VMHost | Sort Name | Select Name, @{N=”NTP”;E={Get-VMHostNtpServer $_} }get-vm -server $vcs Add-VmHostNtpServer -NtpServer ”pool.ntp.org“ -VMHost (Get-VMHost ESX01 )Connect VI Server with credentials: Set DNS Server - Thanks to Luc DekensConnect-VIServer –Server vc.network.test –Credential (Get-Credential) $dnsServers = („192.168.111.3“,“192.168.111.4“)Don´t forget to disconnect your PowerShell session to the VI server, to avoid a session overflow. Get-VMHost | Get-View | %{ To list all tasks for a VI Server and some of their propertiesIf no $ns = Get-View -Id $esx.configManager.networkSystem Get-Task -Server (Connect-VIServer -Server 10.23.112.235) -Status ErrorServer is given, the command disconnects all current PowerShell sessions. $dns = $ns.networkConfig.dnsConfigDisconnect-VIServer [[-Server] <VIServer[]>] [-WhatIf] [-Confirm] [<CommonParameters>] To stop a Task (Example stops the task of removing the VM) $dns.Address = @() Stop-Task -Task (Remove-VM -VM (Get-VM -Name ”MS Win XP SP2“) -Confirm -RunAsync)Disconnect-VIServer -Server $DefaultVIServer foreach($server in $dns.Servers) {Disconnect-VIServer -Server $DefaultVIServer –confirm:$false -> suppress confirmation mes- $dns.Address += $server To wait until a task is completed before continuingsage } Wait-Task -Task (Remove-VM -VM (Get-VM -Name ”MS Win XP SP2“) -Confirm -RunAsync)
  3. 3. Logs & Stats Cluster - 2 Virtual Machines - 2Log Files Move a Cluster Guest OS Operations (requires VMware Tools installed)$esxhost = Get-VMHost -State ”Connected“ Move-Cluster (Get-Cluster MyCluster) -Destination (Get-Folder MyFolder) Get-VMGuest -VM XPVM # Get OS information$log = Get-Logtype -VMHost $esxhost # Get available Log Types Get-VM XPVM | Restart-VMGuest # restart Guest OSGet-Log -Key $log[0] # Get first Log file Remove a Cluster Get-VM XPVM | Suspend-VMGuest # suspend Guest OS Get-Cluster ”CL01” | Remove-Cluster -Confirm:$false$esxhost | Get-Log -Key vmkwarning # Get vmkwarning entriesGet-Log –bundle # Get diagnostic log file bundle aka vm-support VM Storage and removal medias Configure a Cluster Get-HardDisk -VM XPVM # get virtual disks Get-Cluster ”CL01” | Set-Cluster -Name CL02 - -HAEnabled $trueGet all Logfiles with size Get-VM XPVM | New-HardDisk -CapacityKB 1 0240000Get-LogType $esxhost | % {$logdata = (Get-Log $_.Key $esxhost); $size = $logdata. Retrieve a list of DRS rules for the specified clusters # create 10 GB diskLastLineNum - $drsrule = Get-DrsRule -Cluster (Get-Cluster “Production”) -Name ”*Rule99*“ Get-VM XPVM | Get-HardDisk | Set-HardDisk -Persistence NonPersistent$logdata.StartLineNum; ”{0} :{1 }” -f $_.key, $size} $flp = Get-FloppyDrive -VM XPVM New DRS Rule New-FloppyDrive -VM XPVM -HostDevice ‚/dev/fd0‘ -StartConnectedStatistics Get-Cluster „CL01 „ | New-DrsRule -Name Rule99 -KeepTogether $false -VM $vms Remove-FloppyDrive -Floppy $flpGet-StatType -Entity (Get-VmHost ESX01 ) $flp | Set-FloppyDrive -NoMedia # available ESX host statistics Delete DRS Rule $cddrive = Get-CDDrive -VM XPVMGet-StatType -Entity (Get-VM XPVM) # available Virtual Machine statistics Remove-DrsRule $drsrule -Confirm:$false New-CDDrive -VM XPVM -ISOPath ”Path_to_ISOtest.iso“Get-StatInterval # Get available Statistics intervalGet-Stat $esxhost -common -maxsamples 1 -realtime Change DRS Rule Remove-CDDrive -CD $cddrive Set-DrsRule -Rule $drsrule -VM $vms -Enabled $true Set-CDDrive -CD $cddrive -Connected $false # CPU, disk, memory and network statisticsGet-Stat $esxhost -Memory -maxsamples 3 -realtime SnapshotsGet-Stat -Entity (Get-VM XPVM ) -Start 1 /2/2008 -Finish 30/4/2009 -Disk -IntervalSecs 300 Get-VM | Get-Snapshot # To list all the snapshots for all virtual machines Reporting New-Snapshot -VM(Get-VM -Name ”XP SP2“) -Name Patch1 # snapshot a VM Network Get-Snapshot snapshot1 | Remove-Snapshot # remove specific snapshot Get-Snapshot snapshot1 | Remove-Snapshot –RemoveChildren # HTML Basic Report # remove a snapshot with children $a = ”<style>“ Get-VM XPVM | Get-Snapshot | Remove-SnapshotTo list all Virtual Switches attached to a VM and some of their properties # remove all snapshots of vm $a += ”body { background-color:#EEEEEE; }”use: $a += ”body,table,td,th { font-family:Tahoma; color:Black; Font-Size:10pt }”Get-VirtualSwitch -VM (Get-VM -Name ”VM1”) $a += ”th { font-weight:bold; background-color:#CCCCCC; }” Change Snapshot Set-Snapshot -Snapshot snapshot1 -Name ‘AfterPatch1‘ -Description ”After Patch“To create a new Virtual Switch: $a += ”td { background-color:white; }”New-VirtualSwitch -VMHost (Get-VMHost -Name ESX1 ) -Name vSwitch02 $a += ”</style>“ Custom Fields New-CustomField -Entity (Get-VM -Name ”VM1”) -Name CustFieldname -Value 100To Remove a Virtual Switch: # Export Table Report as HTML File$vs = Get-VirtualSwitch -VMHost (Get-VMHost -Name ESX1 ) -Name vSwitch01 $report | ConvertTo-Html -head $a | Out-File ”report.htm“ Read Custom Field (Get-VM ”VM1”).CustomFields.get_item(”CustFieldname“)Remove-VirtualSwitch -VirtualSwitch $vs # Send SMTP MailTo change the configuration of a Virtual Switch: $msg = new-object Net.Mail.MailMessage Set Custom Field Get-VM ”VM1” | Set-CustomField -Name CustFieldname -Value 10$vs = New-VirtualSwitch -Host (Get-VMHost ESX1 ) -Name VirtSwitch # optional AttachmentSet-VirtualSwitch -VirtualSwitch $vs -MTU 500 $att = new-object Net.Mail.Attachment(”c: report.csv“) Remove Custom Field $msg.Attachments.Add($att) Remove-CustomField -Entity (Get-VM -Name ”VM1”) -Name CustFieldnameTo list all the port groups and some of their properties:$vs = Get-VirtualSwitch -VMHost (Get-VMHost -Name ESX1 ) -Name vSwitch02 # Mailserver, Sender and Receiver VMware ToolsGet-VirtualPortGroup -VirtualSwitch $vs $smtp = new-object Net.Mail.SmtpClient(”smtpserver.domain.test) Get-VMGuest XPVM| Update-Tools # Updates VMware Tools $msg.From =“somebody@yourdomain.com“ Get-VMGuest XPVM| Mount-Tools # mount VMware Tools CD-ROMTo add a new port group to a virtual switch: $msg.To.Add(”somebody@theirdomain.com“)$vs = Get-VirtualSwitch -VMHost (Get-VMHost -Name ESX1 ) -Name vSwitch02 Get-VMGuest XPVM| DisMount-Tools # unmount VMware Tools CD Update Manager$vpg = New-VirtualPortGroup -VirtualSwitch $vs -Name VPG1 # Subject & Body Content $msg.Subject = ”Virtual Infrastructure Report“Remove-PortGroup $msg.Body = ”Body Text: Please find the VM Report attached“Set-PortGroup $smtp.Send($msg) # Send the EmailESX Host Network Configuration if ($att) {$att.dispose()} # Clear Attachment locking Important: Because of an incompatibility issue with PowerCLI Version$hostnet = Get-VMHostNetwork (Get-VmHost ESX01 )New-VMHostNetworkAdapter -PortGroupVMKernel -VirtualSwitch $vs -IP 192.168.5.10 1.5 you have to use VI Toolkit Version 1.0 at the moment to work with Virtual Machines - 1-SubnetMask 255.255.255.0 the Update Manager extensionSet-VmHostNetwork -Network $hostnet -VMKernelGateway 192.168.5.254 -DomainNamedomain.test -HostName ESX01 -DnsFromDhcp $false Choose ”Install VMware Update Manager Toolkit“ during installation ofVMware Update Manager Plugin from VI Client.Change Physical Network Settings (100 MBit, Full Duplex) Add-PSSnapIn VMware.VumAutomationGet-VMHostNetwork | Select PhysicalNic | Set-VMHostNetworkAdapter -Duplex „Full“ To list VM’s on the connected VI Server and some of there properties # To load the PowerShell Snapin for Update Manager-BitRatePerSecMb 100 Get-VM # show all VMs of the currently connected instance Get-Command -PSSnapIn VMware.VumAutomation Get-Cluster CL1 | Get-VM # show all VMs running in Cluster CL1 # Get all CmdLets ofUpdate Manager Get-VmHost ”ESX01” | Get-VM # show all VMs registered on host ESX01 Get not compliant Updates ofVMware ESX Host Cluster - 1 Change the configuration of a VM (Get-Compliance (Get-VMHost (Read-Host “ESX Server”))).NotCompliantUpdates Set-VM -VM (Get-VM -Name ”Win XP SP1”) -Name ”Win XP SP2“ -GuestId ”winXPProGuest“ -Description ”My updatedWin XP virtual machine.“ VMware.VUMautomation CmdLets Attach-Baseline, Detach-Baseline, New-BaselineTo list all the Clusters on the connected VI Server and some of there Change VM Power State Download-Update Get-VM XPVM | Start-VM # Start a VMproperties Get-Baseline, Set-Baseline Get-VM XPVM | Start-VM -runasync # Start a VM asynchron (not waiting for task ending)Get-Cluster Get-Compliance Get-VM XPVM | Stop-VM # Stop a VM Get-UpdateTo add a new Cluster Stop-VM -VM XPVM -confirm:$false # Stop VM without asking Get-VumConfigNew-Cluster -Name MyCluster -DRSEnabled -DRSMode FullyAutomated Get-VM | Suspend-VM # Suspend a VM Set-VumConfig Remediate-Inventory Scan-Inventory
  4. 4. Provision VM Sort, Filter & Format Invoke - VMScriptTo create a new VM Filtering PowerCLI required 1.5 with VIX API installed$esxhost = Get-VMHost ”ESXHost01 .mydomain.com“ where-object, where or ? Get-Datastore | where-object {$_.FreeSpaceMB -le 5120} Executes the specified PowerShell script in the guest OS of each of theNew-VM -Name XPVM -VMHost $esxhost -DiskMB 4000 -MemoryMB 256 Get-Datastore | ? {$_.FreeSpaceMB -le 5120} specified virtual machines.To Remove a VM: Level of accessRemove-VM ( Get-VM “myVM” ) –DeleteFromDisk Sorting 1) Read access to the VM including folder. (you need to be able to run Get-VM after Get-datastore | sort Name all)Templates 2) Virtual Machine.Interaction.Console Interaction privilege$template = Get-Template -Name Templ* -Location (Get-Datacenter DC) Format-Table or ft Get-VM | ft * # show all properties as table 3) Windows guest with up-to-date tools and powered on stateRemove-Template -Template $template 4) Windows PowerShell installed within the Windows guestNew-Template -VM ( Get-VM XPVM ) -Name Template01 -Location (Get-Datacenter DC) Get-VM | ft -autosize # optimized output Format-List or fl # like Format-Table but shows list view instead 5) Network connectivity to the ESX system hosting the VM on port 902Set-Template -Template $template -ToVM 6) User Credentials of ESX Server and Virtual Machine Guest OS # convert Template to VM of table view Get-VM | format-list * # show all properties as listGuest Customization Specification Invoke-VMScript [-ScriptText] <String> [-VM] <VirtualMachine[]> [-HostCredential$osspec = Get-OSCustomizationSpec WinXP Select-Object (or select) and Select-String <PSCredential>] [-HostUser <String>] [-HostPassword <SecureString>] # reads Guest Customization Specification object Get-VM | Select-Object Name, PowerState [-GuestCredential <PSCredential>] [-GuestUser <String>] [-GuestPassword <SecureString>]New-VM -Name MyVM2 -Template Template01 -VMHost ESX01 -OSCustomizationSpec $osspec # selects Name and Powerstate out of all properties [-ToolsWaitSecs <Int32>] [-Server<VIServer[]>] ipconfig /all | select-string ”Physical Address“other OS Customization CmdLets: # Select-String searches for specific string ExampleNew-OSCustomizationSpec Get-VM | ?{$_.powerstate -eq ”PoweredOn“} | measure-object Invoke-VMScript -VM (Get-VM myVM) -ScriptText ”dir“ -HostUser root -HostPassword mypassSet-OSCustomizationSpec # counts objects -GuestUser administrator -GuestPassword mypas DataCenter VI PowerScripter Build report with Hashtable $report = @() $hash = @{} Get-VM | % {To list all datacenters from a VMware Infrastructure server $hash = ”” | select VMName, CPU, Memory Download and install VI PowerScripter Pro:Get-Datacenter $hash.VMName = $_.Name http: //www.icomasoft.com/powerscripter $hash.CPU = $_.MemoryMBTo add a new datacenter $hash.Memory = $_.NumCPU no Connect-VIServer or Disconnect-VIServer needed, because handled by PowerScripter.New-Datacenter -Name DC2 Import PowerShell (.ps1 ) or Texfiles with Wizard or put it into the HostScripts or VMscripts folder: $report += $hash %programfiles%“VMwareInfrastructureVirtual Infrastructure ClientPluginsicomasoft Pow-Move a Datacenter } erScripter“Move-Datacenter (Get-Datacenter MyDatacenter) -Destination (Get-Folder MyFolder) $report # Report contains Name, Memory and CPU of the virtual machine parameter within PowerScripter PowerShell files, begin with commentRemove a DataCenter char #, like #--name MigrationGet-Datacenter ”DatacenterDelete“ | Remove-Datacenter #--name = Name for context menu entry #--hideoutput = no PowerShell output windowChange DataCenter Name #--multi = run script once, putting all selected objects (Hosts or VMs) into $multi variableGet-Datacenter ”DatacenterDelete“ | Set-Datacenter -Name Datacenter-old Variables within PowerScripter Script Files $_ # (Current Object - script runs for every selected VMotion Resource Pools object) Move-VM [-Destination <VIContainer>] [-Datastore <Datastore>] [-RunAsync] [-VM] $multi # (array of selected objects (Hosts or VMs)) <VirtualMachine[]> Builtin Reporting CmdLets VMotion virtual machine Get-VM | Out-GridviewIS # visualizes all VMs, allowing sorting, filtering,To list all Resource Pool’s on the connected VI Server and some of their Get-VM myVM | Move-VM -destination (Get-VMHost ESXHost) -confirm:$false exporting andconditional formattingpropertiesGet-ResourcePool VMotion virtual machine async Get-VM | Export-CsvIS -Path c: vms.csv Move-VM -VM (Get-VM ”myVM“) -RunAsync -Destination (Get-VMHost ”ESXHost“) # Exports all VMs with properties into CSV FileTo create a new resource pool Get-VM | Export-ExcelIS -Path c: vms.xls$clusterRootRP = Get-ResourcePool -Location ( Get-Cluster ResearchAndDevelopmentCluster ) Storage VMotion # Exports all VMs with properties into Excel File Get-VM myVM | Move-VM -datastore (Get-Datastore ”DS-Name“) -confirm:$false-Name Resources Connect/Disconnect SSH Session Get-VM | SVMotion-VM -destination (get-datastore TargetDS)New-ResourcePool -Location $clusterRootRP -Name DevelopmentResources Connect-SSH -Server 192.168.1.201 -User root -Password letmein-CpuExpandableReservation $true -CpuReservationMhz 500 -CpuSharesLevel high Cold Migration # connect to a SSH server-MemExpandableReservation $true -MemReservationMB 500 -MemSharesLevel high Get-VM myVM | Stop-VM -confirm:$false Disconnect-SSH # Disconnects SSH Session Get-VM myVM | Move-VM -destination (Get-VMHost ESXHost) -confirm:$false Run-SSHCmd ”vdf -h“ # Run given command within SSH connectionMove a Resource PoolMove-ResourcePool -ResourcePool (Get-ResourcePool RP) -Destination (get-VmHost ESX01 ) Quick Migration Run given command after connecting to SSH Server $vm = Get-VM ”myVM“ # Store VM object in $vm variable Run-SSHCmd ”esxcfg-mpath -l“ -Server 192.168.1.201 -user root -password letmeinDelete a Resource Pool Suspend-VM -VM $vm -confirm:$falseRemove-ResourcePool -ResourcePool (Get-ResourcePool RP) Copy files using the SSH protocol - existing or new SSH Session can # Suspend VMConfigure Resource Pool $vm | Move-VM -Destination (Get-VMHost ESXHost) -datastore ($vm | get-datastore) be usedSet-Resourcepool (Get-Resourcepool -Name ”RP“) -NumCpuShares 2048 -MemLimitMB 4096 Start-VM -VM $vm # Resume VM Run-SCP -Source 192.168.1.201:/etc/vmware/esx.conf -Destination c: ESXhost-config Run-SCP 192.168.1.201:/etc/vmware/esx.conf c:ESXhost-config -user root -password letmein Thanks to: And Thanks to: Alan Renouf, contribution of content Urs Stephan Alder, for hosting the test infrastructure - http://www.virtu-al.net - http://www.d-on-d.com Forbes Guthrie, sharing his great Reference Design VMware Community © and Design by - http://www.vmreference.com/ - for awesome work in publishing scripts and scriptlets www.islogo.de

×