gpt4 book ai didi

powershell - Powershell-导出-CSV外循环,仅最后一行被打印/导出

转载 作者:行者123 更新时间:2023-12-03 01:28:22 29 4
gpt4 key购买 nike

是否可以调整此代码以导出foreach循环外的所有行:

这工作正常(内部循环):

 $vms = Get-VM | Where { $_.State –eq ‘Running’ } | Select-Object -ExpandProperty Name 

foreach($vm in $vms) {

# Get network interface details
$out = Get-VMNetworkAdapter -vmname $vm | select VMName, MacAddress, IPAddresses

$vm_name = $out.VMName | Get-Unique
$ip = ($out.IPAddresses | ForEach-Object {
$_ | ? {$_ -notmatch ':'}
}) -join " "
# If more than 1 MAC , put it in same row separated by space (00:15:5D:58:12:5E 00:15:5D:58:12:5F )

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

$results = @()

$comp = Get-WmiObject Win32_ComputerSystem | Select-Object -ExpandProperty name

$obj = New-Object -TypeName psobject
$obj | Add-Member -MemberType NoteProperty -Name "VM NAME" -Value $vm_name
$obj | Add-Member -MemberType NoteProperty -Name "IP ADDRESS" -Value $ip
$obj | Add-Member -MemberType NoteProperty -Name "MAC ADDRESS" -Value $mac
$obj | Add-Member -MemberType NoteProperty -Name "HYPER-V HOST" -Value $comp


$results += $obj

Write-Output $results

$results| Export-Csv -Path "c:\1.csv" -NoTypeInformation -append
}

但是,当我将 $results| Export-Csv -Path "c:\1.csv" -NoTypeInformation -append移到循环外时,
仅最后一行保存为CSV

在循环内部, $results变量包含所有行,当我将此变量移到循环 write-host $results外部时,仅打印(最后)一行

最佳答案

对于它的值(value),您的代码可以精简很多。您的许多步骤都是不必要的:

$results = Get-VM | Where State –eq Running | Get-VMNetworkAdapter | ForEach-Object {
[pscustomobject]@{
'VM NAME' = $_.VMName
'IP ADDRESS' = ($_.IPAddresses -notmatch ':') -join ' '
'MAC ADDRESS' = ($_.MacAddress -replace '(..)(..)(..)(..)(..)','$1:$2:$3:$4:$5:') -join ' '
'HYPER-V HOST' = $env:COMPUTERNAME
}
}

$results | Export-Csv -Path "c:\1.csv" -NoTypeInformation

笔记:
  • 您可以将Get-VM直接返回的虚拟机通过管道传输到Get-VMNetworkAdapter
  • 如果您过滤单个属性,则不需要Where-Object的脚本块。 Where State -eq RunningWhere { $_.State -eq 'Running' }容易编写和读取。
  • $_.IPAddresses -notmatch ':'-notmatch这样的运算符可在数组上工作。 'a','b','0','c' -notmatch '\d'将返回'a','b','c'
  • -replace也是如此。 'a0','b1','c2' -replace '\d',''将返回return 'a','b','c'。根本不需要foreach循环。
  • $env:COMPUTERNAME应该比使用WMI获得计算机名称
  • 更快
  • 您在脚本块(例如ForEach-Object {...}脚本块)中创建的任何未分配给变量的对象都将出现在脚本块的输出中。这就是$results = ... | ForEach-Object {...}起作用的原因。无需使用@()显式创建数组并将值添加到其中。
  • 将哈希表强制转换为[pscustomobject]比使用Add-Member容易得多。
  • 关于powershell - Powershell-导出-CSV外循环,仅最后一行被打印/导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60450293/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com