所以我已经知道这个代码是
Set-VM -Name "localhost" -Notes "127.0.0.1"
使用
$ipAddress = get-vm | where { $_.state -eq 'running'} | get-vmnetworkadapter | Select @{Name="IP";Expression={$_.IPAddresses | where {$_ -match "^192\."}}} | Sort VMName
获取我的 IP 地址
IP
--
127.0.0.1
完整的代码如下
$ipAddress = get-vm | where { $_.state -eq 'running'} | get-vmnetworkadapter | Select @{Name="IP";Expression={$_.IPAddresses | where {$_ -match "^192\."}}} | Sort VMName
Set-VM -Name "server1" -Notes "$ipAddress"
但是当我添加 foreach 循环时
$vms = Get-VM
$ipAddress = get-vm | where { $_.state -eq 'running'} | get-vmnetworkadapter | Select @{Name="IP";Expression={$_.IPAddresses | where {$_ -match "^192\."}}} | Sort VMName
foreach ($vm in $vms) {
Set-VM -Name "$vm" -Notes "$ipAddress"
}
为每个虚拟机产生类似的错误
Set-VM : The specified wildcard character pattern is not valid: VirtualMachine (Name = 'server1') [Id = 'de0994fb-c19b-48a3-9389-fd595bd3dc43']
At line:2 char:5
+ Set-VM -Name "$vm" -Notes "$ipAddress"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Set-VM], VirtualizationException
+ FullyQualifiedErrorId : Unspecified,Microsoft.HyperV.PowerShell.Commands.SetVM
我不明白为什么它可以在没有循环的情况下工作,但不能
编辑:按照 Pimp Juice IT 的建议回应
VirtualMachine (Name = 'server1') [Id = 'de0994fb-c19b-48a3-9389-fd595bd3dc43'] VirtualMachine (Name = 'server2') [Id = 'ecb80604-1f4a-4493-97cd-14d474baca30'] VirtualMachine (Name = 'server3') [Id = '71a01492-f70e
-420e-9db8-1718ac5d9b41'] VirtualMachine (Name = 'server4') [Id = '500387d7-95e0-44a6-9819-425d4b7af876'] VirtualMachine (Name = 'server5') [Id = '4eef3925-1ae5-4410-8fee-2f99bbfd7ec5'] VirtualMachine (Name = 'serv
er6') [Id = '337f1016-4001-457e-b231-b84173efd695'] = Get-VM
@{IP=192.168.0.39} = get-vm | where { .state -eq 'running'} | get-vmnetworkadapter | Select @{Name=
IP;Expression={.IPAddresses | where { -match ^192\.}}} | Sort VMName
foreach (VirtualMachine (Name = 'server6') [Id = '337f1016-4001-457e-b231-b84173efd695'] in VirtualMachine (Name = 'server1') [Id = 'de0994fb-c19b-48a3-9389-fd595bd3dc43'] VirtualMachine (Name = 'server2') [Id = 'e
cb80604-1f4a-4493-97cd-14d474baca30'] VirtualMachine (Name = 'server3') [Id = '71a01492-f70e-420e-9db8-1718ac5d9b41'] VirtualMachine (Name = 'server4') [Id = '500387d7-95e0-44a6-9819-425d4b7af876'] VirtualMachine (
Name = 'server5') [Id = '4eef3925-1ae5-4410-8fee-2f99bbfd7ec5'] VirtualMachine (Name = 'server6') [Id = '337f1016-4001-457e-b231-b84173efd695']) {
Set-VM -Name VirtualMachine (Name = 'server6') [Id = '337f1016-4001-457e-b231-b84173efd695'] -Notes @{IP=192.168.0.39}
}
答案1
您正在将 VM 对象传递给 Name 参数,该参数需要一个字符串。VM 参数就是为此目的而设的。
Set-VM -VM $vm
假设您想要将 192 个 IP 地址添加到每个 VM 的注释中,那么我会这样做。如果 VM 是多宿主的,它将用逗号分隔地址。
$vms = Get-VM | where { $_.state -eq 'running'}
foreach ($vm in $vms) {
Set-VM -VM $vm -Notes $($vm.NetworkAdapters.IPAddresses -match "^192\." -join ',')
}
希望有帮助