我的VM具有多个IP / MAC地址
我正在使用以下代码来获取多个IP / MAC地址:
$vms=Get-VM | Where { $_.State –eq ‘Running’ } | Select-Object -ExpandProperty Name
foreach($vm in $vms) {
$out=Get-VMNetworkAdapter -vmname $vm | select VMName, MacAddress, IPAddresses
$virtm=$out.VMName
$ip=$out.IPAddresses
if ($ip.Count -gt 1){
foreach($i in $ip.Count) {
if ($ip -match ':'){
$ip = $ip | ?{$_ -notmatch ':'}
}
}
$ip = $ip -join " "
$virtm = ($virtm -split '\n')[0]
}
else {
$ip=$out.IPAddresses
}
$mac=$out.MacAddress
if ($mac.count -gt 1) {
$mac = $mac -join " "
}
foreach($m in $mac) {
$mac=$m.Insert(2,":").Insert(5,":").Insert(8,":").Insert(11,":").Insert(14,":")
}
Write-Output "$virtm, $ip, $mac"
此代码可以正常工作,希望它可以仅将列添加到第一个MAC地址
当前输出:
OAP80, 192.168.87.45 192.168.1.45, 00:15:5D:58:12:5E 00155D58125F
我想将列添加到特定VM的所有其他MAC地址
所需的输出
OAP80, 192.168.87.45 192.168.1.45, 00:15:5D:58:12:5E 00:15:5D:58:12:5F
我尝试在将集合转换为字符串之前添加
:
$mac=$out.MacAddress
$mac=$mac.Insert(2,":").Insert(5,":").Insert(8,":").Insert(11,":").Insert(14,":")
但是得到:
Exception calling "Insert" with "2" argument(s): "Collection was of a fixed size."
At line:35 char:6
+ $mac=$mac.Insert(2,":").Insert(5,":").Insert(8,":").Insert(11,":").Insert(1 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : NotSupportedException
最佳答案
简而言之,您可以执行以下操作将冒号放在Mac地址中,并将它们合并为单个字符串,并以空格作为分隔符:
$mac = ($out.MacAddress | ForEach-Object {
$_.Insert(2,":").Insert(5,":").Insert(8,":").Insert(11,":").Insert(14,":")
}) -join ' '
Write-Output "$virtm, $ip, $mac"
关于powershell - Hyper-V Powershell-将冒号添加到MAC地址,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60435381/