Hyper-V Powershell-将冒号添加到MAC地址

问题描述 投票:1回答:4

我的虚拟机具有多个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
powershell hyper-v
4个回答
1
投票

简而言之,您可以执行以下操作将冒号放在Mac地址中,并将它们合并为单个字符串,并以空格作为分隔符:

$mac = ($out.MacAddress | ForEach-Object {
    $_.Insert(2,":").Insert(5,":").Insert(8,":").Insert(11,":").Insert(14,":")
}) -join ' '

Write-Output "$virtm, $ip, $mac"

1
投票

怎么样? “ $&”表示整个匹配项。行尾也有负前行,因此冒号不会放在末尾。

$mac = '00155D58125F','00155D58125G','00155D58125H'
$mac = $mac -replace '..(?!$)','$&:' 
$mac 

00:15:5D:58:12:5F
00:15:5D:58:12:5G
00:15:5D:58:12:5H

0
投票

正如Lee_Dailey正确指出的:$out.MacAddress包含字符串数组。您想遍历每个元素并在将冒号连接成单个字符串之前插入冒号:

$mac = $out.MacAddress
$macWithColons = foreach ($m in $mac) 
{
    $m.Insert(2, ":").Insert(5, ":").Insert(8, ":").Insert(11, ":").Insert(14, ":")
}
$macWithColons -join " "

0
投票

foreach您不需要$mac只需使用after(如果mac格式为XX-xx-xx-xx-xx-xx)

if ($mac.count -gt 1) {

    $mac = $mac -join " "
        }
$mac.Replace('-',':')

您可以执行此操作(如果Mac的格式为xxxxxxxxxxxx):$mac=$out.MacAddress|foreach{($_.Insert(2,":").Insert(5,":").Insert(8,":").Insert(11,":").Insert(14,":"))-join " "}

并且可以删除它:

if ($mac.count -gt 1) { $mac = $mac -join " " } foreach($m in $mac) { $mac=$m.Insert(2,":").Insert(5,":").Insert(8,":").Insert(11,":").Insert(14,":") }
© www.soinside.com 2019 - 2024. All rights reserved.