[PowerShell Utils] Create a list of virtual machines based on configuration read from a CSV file in Hyper-V

Hello everyone, this is the third post of the series. .

 

Background

===============

In my solution, I have 15 Windows hosts. I need to configure them from the OS installation to configure fail over cluster and then create and run VMs on them. Without scripting, manually complete related tasks would be very bored and easy to make mistakes. I started using PowerShell and it really helped ease the pain.

 

What can this one do

===============

I need to create about 20 VMs, they have different settings, such as number of CPU, Memory amount, Virtual Disk Size, Location, etc. I don’t want to mannually configure them all in GUI. So…

This script will read a CSV file, and get the configuration for each VM, and then automatically create all the VMs based on your requirement.

As always, everything in one click!

 

Logic Intro

===============

Nothing special, just read CSV and create VMs one after another.

The hard part is the usage of each of the cmdlet involved. Took me most of the time.

Note the (Invoke-Expression $vairable.member), this is special.

 

Script is here

===============

$b = Import-Csv D:\XYZABC\CreateVMs.csv -Header VMName, Processor, RAM, VHDSize, VMLocation, VirtualSwtich

Foreach ( $vm in $b ) 
{    
    New-Item -Path $vm.VMLocation -ItemType directory -force -ErrorAction SilentlyContinue
    New-VM $vm.VMName -path $vm.VMLocation
    New-VHD -Path ("{0}/{1}/{1}.vhdx" -f $vm.VMLocation, $vm.VMName) -SizeBytes (Invoke-Expression $vm.VHDSize)
    Add-VMHardDiskDrive -VMName $vm.VMName -ControllerType SCSI -ControllerNumber 0 -path ("{0}/{1}/{1}.vhdx" -f $vm.VMLocation, $vm.VMName)
    Get-VM $vm.VMName | Set-VMMemory -DynamicMemoryEnabled 0 -StartupBytes (Invoke-Expression $vm.RAM)
    Get-VM $vm.VMName | Set-VMProcessor -count $vm.Processor
    Get-VM $vm.VMName | Add-VMNetworkAdapter -SwitchName $vm.VirtualSwtich
}
 

This is what the CSV look like.

image

 

Further

============

I know SCVMM should be better at this task. I will learn it, and post update on this topic as soon as I tuned how to make SCVMM able to do the same thing on a windows failover cluster.

 

Please forgive me for not listing all the articles that supported me on writing out this script. There are so many… …

posted on   中道学友  阅读(425)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
历史上的今天:
2011-11-25 如何开放Hyper-V服务的远程连接权限给别人?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

技术追求准确,态度积极向上

点击右上角即可分享
微信分享提示