【发布时间】:2021-02-03 23:45:24
【问题描述】:
我们正在为相当大的安装(包括 Hyper-V 虚拟机)收集系统信息。作为这项工作的一部分,我们正在清点 VM 的属性,并且我们希望将 IP 地址(或第一个 IP 地址)与 VM 相关联。
为此,我们有以下脚本,其中详细说明了我们要收集的项目。然后,对于组的每个元素,我们要添加(第一个)网络适配器信息。但是,您在该脚本中间看到的 Add-Member 似乎没有任何作用;无论我们是否包含该 ForEach 或省略它,脚本都会输出相同的内容,我不明白为什么。对此类对象使用 Add-Member 是否无效(虽然没有错误......)?你能指出这个脚本可能出错的地方吗?
$VMs = Get-VM `
| Select @{Name='Hostname';Expression={$(hostname)}} `
, VMName, VMId, Id `
, AutomaticStartAction, Uptime, OperationalStatus `
, PrimaryOperationalStatus, Status, ReplicationHealth, ReplicationState `
, CheckpointType, VirtualMachineType, VirtualMachineSubType `
, State, HardDrives, MemoryMaximum, MemoryMinimum,MemoryStartup `
, ProcessorCount, Path,SizeOfSystemFiles, ReplicationMode `
, ResourceMeteringEnabled, Version, FibreChannelHostBusAdapters `
, DynamicMemoryEnabled, CreationTime, IsDeleted
ForEach ($VM in $VMs) {
$Adapters=($VM | Get-VMNetworkAdapter)
$firstAdapter = "Yes"
ForEach ($Adapter in $Adapters) {
if ($firstAdapter -eq "Yes") { <# Prevent fail if more than one adapter is present. #>
$ip4 = $Adapter.IPAddresses[0]
$ip6 = $Adapter.IPAddresses[1]
$VM | Add-Member -MemberType NoteProperty -Name Adapter -value $Adapter.Name
$VM | Add-Member -MemberType NoteProperty -Name IPAddress -value $Adapter.IPAddresses[0]
$VM | Add-Member -MemberType NoteProperty -Name IP6 -value $Adapter.IPAddresses[1]
$firstAdapter = "No"
}
}
}
$VMs | ConvertTo-Csv -NoTypeInformation `
| Set-Content -Path \path\to\myfile.csv
顺便说一句,如果我的新手从使用 ForEach() 的测试中显示出除了第一个之外的所有内容...我很乐意看到有关更好方法的建议。
感谢您的宝贵时间。
【问题讨论】:
-
我才发现我没有选择网络信息。对脚本进行重组,将选择移到最后,解决了这个问题。我将投票结束我的愚蠢问题。
标签: powershell hyper-v