我有多个IP/MAC地址的VM
我使用这段代码获取多个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发布于 2020-02-27 15:09:00
简而言之,您可以这样做,在Mac地址中放置冒号,并将它们合并为单个字符串,并以空格作为分隔符:
$mac = ($out.MacAddress | ForEach-Object {
$_.Insert(2,":").Insert(5,":").Insert(8,":").Insert(11,":").Insert(14,":")
}) -join ' '
Write-Output "$virtm, $ip, $mac"发布于 2020-02-27 15:14:21
这个怎么样?"$&“指的是整个比赛。行尾也有负值,所以冒号不会放在末尾。
$mac = echo 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发布于 2020-02-27 14:43:52
您不需要foreach用于$mac,只需使用后(如果mac格式为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,":") }https://stackoverflow.com/questions/60435381
复制相似问题