# https://www.say-tech.co.jp/contents/blog/yamanxworld/2026vol169 # Add ConvertTo-Subnet function param( [Parameter(Mandatory)] [string]$VMName ) function ConvertTo-SubnetMask { param( [string]$PrefixLength ) if ($PrefixLength -notmatch '^\d+$' -or [int]$PrefixLength -lt 0 -or [int]$PrefixLength -gt 32) { return $PrefixLength } $mask = [uint32]::MaxValue -shl (32 - [int]$PrefixLength) $bytes = [BitConverter]::GetBytes($mask) [Array]::Reverse($bytes) return ($bytes -join '.') } $vm = Get-VM -Name $vmname if($vm.State -ne "Running") { Write-Host "VM $($VMName) is not Running." exit } #$vmName = Read-Host "Specify the name of your virtual machine" $ns = "root\virtualization\v2" $vsvms = Get-WmiObject -Namespace $ns -Class Msvm_VirtualSystemManagementService $vmcs = Get-WmiObject -Namespace $ns -Class Msvm_ComputerSystem -Filter "ElementName='$vmName'" if (-not $vmcs) { Write-Host "Error: VM $vmname is missing." exit 1; } $vs_settingdata = ($vmcs.GetRelated("Msvm_VirtualSystemSettingData", "Msvm_SettingsDefineState", $null, $null, "SettingData", "ManagedElement", $false, $null) | %{$_}) $et_settingdata = $vs_settingdata.GetRelated("Msvm_SyntheticEthernetPortSettingData") $vm_netconf = ($et_settingdata.GetRelated("Msvm_GuestNetworkAdapterConfiguration", "Msvm_SettingDataComponent", $null, $null, "PartComponent", "GroupComponent", $false, $null) | % {$_}) $yesno = Read-Host "Enable DHCP? (y/n[n])" if ($yesno.toLower() -eq "y") { $vm_netconf.DHCPEnabled = $true $vm_netconf.DNSServers = @() } else { $vm_netconf.DHCPEnabled = $false $vm_netconf.IPAddresses = (Read-Host "Specify static ipv4 address") $vm_netconf.Subnets = (Read-Host "Specify subnetmask") $vm_netconf.Subnets = ConvertTo-SubnetMask $vm_netconf.Subnets $vm_netconf.DefaultGateways = (Read-Host "Specify default gateway") $vm_netconf.DNSServers = @((Read-Host "Specify preferred dns server")) -split '\s*,\s*' } $ret = $vsvms.SetGuestNetworkAdapterConfiguration($vmcs.Path, $vm_netconf.GetText(1)) if ($ret.ReturnValue -ne 0) { Write-Host "Error: something went wrong" } Get-CimInstance -Namespace $ns -ClassName Msvm_GuestNetworkAdapterConfiguration | Where { $_.InstanceID -like "*$($vm.vmId)*" }|Select DHCPEnabled,IPAddresses,Subnets,DefaultGateways,DNSServers