温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

PowerCLI脚本,利用哈希表对参数进行转换

发布时间:2020-07-10 19:04:12 来源:网络 阅读:660 作者:forsk 栏目:系统运维

在使用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"
}

<#假若集群的主机有多个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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI