PowerCLI腳本,利用哈希表對參數進行轉換
阿新 • • 發佈:2018-08-03
存儲 HERE 創建虛擬機 哈希 滿足 fir 主機 centos7 shell腳本 在使用PowerCLI的編寫powershell腳本的過程中,有這樣一個需求:例如需要重啟一個指定的虛擬機,運行腳本時輸入的參數,參數為虛擬機的名字,但是虛擬機的名字在建立的時候可能是千奇百怪,我們想把參數與虛擬機名稱對應,實現參數能夠自動轉化轉換為想要的虛擬機的名字。
powershell的哈希表可以滿足這種需求。
還有這樣一個需求:在創建虛擬機的時候,我們不僅要輸入主機參數,LUN參數,模板參數。這些參數的名字不好記憶,或者太長,使用時比較麻煩;也可以通過哈希表的轉換,將簡潔的參數在腳本內部自動轉換為對應的參數。
powershell的哈希表可以滿足這種需求。
還有這樣一個需求:在創建虛擬機的時候,我們不僅要輸入主機參數,LUN參數,模板參數。這些參數的名字不好記憶,或者太長,使用時比較麻煩;也可以通過哈希表的轉換,將簡潔的參數在腳本內部自動轉換為對應的參數。
eg:如下是創建虛擬機是哈希表的應用
#定義參數 param( [string]$VMname,[string]$vmhostname,[string]$datastore, [string]$template ) #在命令窗口中添加powercli模塊 try{ add-pssnapin vmware.vimautomation.core -ErrorAction SilentlyContinue } catch{} #定義模板哈希表 $TemplateGroup=@{"centos"="centos7.4";"windows"="server2008sp1"} $Template=$TemplateGroup["$template"] #定義主機哈希表 $HostName=@{"1.23"="192.168.1.23";"1.24"="192.168.1.24";"1.56"="192.168.1.56"; } $VMHost=$HostName["$vmhostname"] #定義存儲哈希表 $DatastoreGroup=@{"A"="storage1";"B"="storage2";"C"="storage3" "D"="storage4";"E"="storage-7","storage-5","storage-6" } <#假若集群的主機有多個LUN,我們可以隨機選取一個值,eg:E對應的有多個LUN,我們使用時可以使用Get-Random來隨機獲取一個LUN#> if($datastore -eq "E"){ $Datastore=Get-Random $DatastoreGroup["$datastore"] }else{ $Datastore=$DatastoreGroup["$datastore"] } #連接Vsphere Connect-VIServer -server serverIP -Protocol https -User username -Password password #根據模板創建VM if($template -eq "windows"){ new-vm -name $VMname -host $VMHost -template $Template -datastore $Datastore -OSCustomizationSpec win2008 }else{ new-vm -name $VMname -host $VMHost -template $Template -datastore $Datastore } #斷開連接 Disconnect-VIServer -server serverIP -Confirm:$false
執行命令時,就可以使用簡潔易於記憶的參數
.\newvmscript.ps1 vmname 1.23 windows E
or
.\newvmscript.ps1 -VMname vmname -vmhostname 1.23 -datastore E -template windows
eg:如下為一個重啟業務機器的例子
param([string]$Name) try{ add-pssnapin vmware.vimautomation.core -ErrorAction SilentlyContinue } catch{} $NameGroup=@{"業務域名1"="虛擬機名稱1";"業務域名2"="虛擬機名稱2"; } $VMName=$NameGroup["$Name"] connect-viserver -server serverip -user username -password password -port 443 Restart-VM -VM $VMName -Confirm:$false -RunAsync Disconnect-VIServer -Confirm:$false
運行腳本時:.\restartscript.ps1 業務域名1
PowerCLI腳本,利用哈希表對參數進行轉換