当前位置:首页 > VMware > 正文内容

Powershell批量给VMware虚拟机挂载磁盘并初始化

邓鹏8个月前 (02-19)VMware333

需要实现通过Powershell脚本给VMware虚拟机批量挂载磁盘并且初始化需要满足如下要求。

1 Windows系统上需要导入VMware Powershell模块。建议导入用户个人Powershell模块目录下,点击下载模块

#Powershell模块版本名称为:VMware-PowerCLI-13.0.0-20829139.zip 需要解压后把解压内容放置到如下创建Modules目录下。
PS C:\Users\dengpeng> $env:PSModulePath #查看路径
C:\Users\dengpeng\Documents\WindowsPowerShell\Modules;C:\Program Files\WindowsPowerShell\Modules;C:\Windows\system32\WindowsPowerShell\v1.0\Modules
#根据如上输出结果,\WindowsPowerShell\Modules需要在Documents目录下创建。
#输入命令  Set-PowerCLIConfiguration -Scope User -ParticipateInCEIP $True
#输入命令导入模块   Import-Module VMware.PowerCLI 即可导入成功

2 如下为我测试环境。

image.png

通过命令批了创建10个测试虚拟机。

#定义连接VC
$vCenterIp = "172.17.3.242"
$vCenterUsername = "administrator@vsphere.local"
$vCenterPassword = "P@ssw0rd"

Connect-VIServer -Server $vCenterIp -User $vCenterUsername -Password $vCenterPassword -Protocol https
Get-VM

#创建10台测试虚拟机,以CVAD-VDI-###开头。
1..9 | foreach  {New-VM -Name CVAD-VDI-00$_ -ResourcePool 172.17.3.200 -Datastore Datastore_new -NumCpu 2 -MemoryMB 4 -NetworkName "VM Network" -Floppy -CD -DiskStorageFormat Thin}

#批了删除创建的虚拟机
Remove-VM -VM VDI-* -DeletePermanently

批量创建测试虚拟机,如下图,如需批了删除,请运行 Remove-VM -VM  CVAD-VDI-*   -DeletePermanently image.png

如下为VMware显示界面。

image.png

3 虚拟机都需要安装VMTloos工具才行。

然后运行如下Powershell脚本即可,其中部分信息需要修改。

param(
        [Parameter(Mandatory=$true, HelpMessage="The Name prefix of Citrix virtual machine", Position=0)]
        [string]
        $vmprefix,
        [Parameter(Mandatory=$true, HelpMessage="The number of the fisrt virtual machine", Position=1)]
        [int]
        $startnum,
        [Parameter(Mandatory=$true, HelpMessage="The number of the last virtual machine", Position=2)]
        [int]
        $endnum,
        [Parameter(Mandatory=$true, HelpMessage="The number of the last virtual machine", Position=2)]
        [int]
        $diskszie
    )
#the script to initilize D drive in virtual machine
#Get-Partition -DriveLetter 'E' | Set-Partition -NewDriveLetter 'P' |Out-Null
$script = @"
Get-Disk  | Where PartitionStyle -eq "raw" | Initialize-Disk -PartitionStyle GPT -PassThru | New-Partition -UseMaximumSize -AssignDriveLetter | Format-Volume -FileSystem NTFS   -NewFileSystemLabel  "个人数据盘"
"@
######################################################################################
#VC
$VC_IP="172.17.3.242"                                    #vCenter登录IP
$VC_USER="administrator@vsphere.local"    #vCenter登录用户名
$VC_PWD="password"                                        #vCenter登录密码
#$DataStore="Local-01"                   #指定存储添加磁盘,若跟虚拟机存储位置保值一致,注释掉即可。
#window
$GuestUser="administrator"                            #添加磁盘虚拟机本地管理员账号
$GuestPassword="password"                                #密码
#$diskszie=""
#disk
$diskcounts="2"                                                #1代表未添加磁盘前,系统磁盘数量。MCS批量发布后,默认两块

######################################################################################
#the file to save virtual machine uuid to activate Chrome
$datevalue = get-date -Format "yyyyMMddHHmm"
#$filename = "C:\Users\citrixadmin\Desktop\VM-disk\" + $datevalue + "chrome.csv"
echo "Serial Number (mandatory),Asset Tag" > $filename
if ( $startnum -le $endnum ) {
    #Connect-VIServer hk-hco-vcsa-01
    $VC = connect-viserver -server $VC_IP -user $VC_USER -password $VC_PWD
    for($i = $startnum; $i -le $endnum; $i++) {
        $vmname = $vmprefix + '{0:d3}' -f $i    #表示虚拟机名称最后几位数例如CVAD-VDI-### 代表3
        $nu =  '{0:d3}' -f $i                                        #表示虚拟机名称最后几位数例如CVAD-VDI-### 代表3
        $Exists = get-vm -name $vmname -ErrorAction SilentlyContinue
        If ($Exists) {
            $vmuuid = (get-vm -Name $vmname | Get-VIew).config.uuid
            $vmuuid = $vmuuid.replace('-', '')
            $uuidlen = ${vmuuid}.length
            $result = "VMware-"
            for ($a = 0; $a -le $uuidlen; $a = $a + 2) {
                if ($a -eq 14) {
                    $middle = '-'
                }
                elseif ($a -eq 30) {
                    $middle = ',' + $vmname
                }
                else {
                    $middle = ' '
                }
                $result = $result + $vmuuid[$a] + $vmuuid[$a + 1] + $middle
            }
            echo ${result} >> $filename

            $diskcount = (Get-HardDisk -vm $vmname).count
            if ($diskcount -eq $diskcounts) {
                #$dsname = (Get-HardDisk -vm $vmname | Get-Datastore).Name
                #New-HardDisk -VM $vmname -CapacityGB $diskszie -StorageFormat Thin -DataStore  $DataStore |Out-Null  #数据盘和系统不同存储
                New-HardDisk -VM $vmname -CapacityGB 20 -StorageFormat Thin   | Out-Null  #数据盘和系统同一存储
                $OSversion = (get-vm -Name $vmname | Get-view).config.GuestFullName
                if ( $OSversion -like "*Windows*") {
                    $vm = Get-VM -Name $vmname
                    if ($vm.PowerState -eq "PoweredOff") {
                        Start-VM -VM $vm -Confirm:$false
                        Start-Sleep -s 60
                    }
                    #Invoke-VMScript -ScriptText $script -VM $vmname  -GuestUser $GuestUser -GuestPassword $GuestPassword -ScriptType PowerShell |Out-Null
                    Invoke-VMScript -ScriptText $script -VM $vmname  -Server  $VC_IP -ScriptType PowerShell
                    Start-Sleep -s 2
                     Write-Host [1] VM数据盘添加列表: -ForegroundColor Green
                    Write-Host  ${vmname} 添加数据盘完成 -ForegroundColor Green
                }                
            }
            else {
                 Write-Host [2] VM数据盘已完成列表: -ForegroundColor Green
                #echo "Please check if the virtual machine ${vmname} is with 200 GB drive, or you can add the disk manually."
                Write-Host  ${vmname} 已完成数据盘完成
            }
        }
        else {
        
            #echo "${vmname} does not exist"
             #Write-Host [3] VM 列表: -ForegroundColor Green
            Write-Host $nu  ${vmname} 没有查询到 -ForegroundColor Red
        }

    }

}
else {
    echo "The start number should be less than end number!"
}

运行显示效果如下,表示虚拟机前缀为CVAD-VDI-  最后表示三位### 在脚本里面已经设置。设置开始位数和结束位数即可执行。重复添加也无影响,脚本已经做了相应判断,已添加磁盘会自动略过。200为磁盘容量,默认GB为单位。

image.png


扫描二维码推送至手机访问

版权声明:本文由PowerShell中文社区发布,如需转载请注明出处。

本文链接:https://www.powershell.com.cn/?id=96

标签: 运维
分享给朋友:
返回列表

上一篇:Powershell导入VMware强大的管理工具-PowerCLI

没有最新的文章了...

“Powershell批量给VMware虚拟机挂载磁盘并初始化” 的相关文章

PowerShell一键自动化部署ESXI及VSAN

PowerShell一键自动化部署ESXI及VSAN

    脚本自动化部署vSphere和配置VSAN集群环境,可以完成以下一些操作:    1 部署嵌套的 ESXi 主机:通过 OVA 文件导入和配置多个嵌套 ESXi 主机,设置其网络信息、CPU、内存和磁盘大小,并将...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。