Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

PowerCLI script, using hash table to convert parameters

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

在使用PowerCLI的编写powershell脚本的过程中,有这样一个需求:例如需要重启一个指定的虚拟机,运行脚本时输入的参数,参数为虚拟机的名字,但是虚拟机的名字在建立的时候可能是千奇百怪,我们想把参数与虚拟机名称对应,实现参数能够自动转化转换为想要的虚拟机的名字。

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"}if($datastore -eq "E"){ $Datastore=Get-Random $DatastoreGroup["$datastore"]}else{ $Datastore=$DatastoreGroup["$datastore"]}#连接VsphereConnect-VIServer -server serverIP -Protocol https -User username -Password password#根据模板创建VMif($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 Eor.\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 443Restart-VM -VM $VMName -Confirm:$false -RunAsyncDisconnect-VIServer -Confirm:$false

运行脚本时:.\restartscript.ps1 业务域名1

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 239

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report