想要导出CSV属性的variables

我想build立一个“〜表”来保存有关各种计算机的信息(例如,名称,IP地址和MAC地址,但稍后可能会添加更多信息)。 这是我到目前为止:

$Computers = "Server1", "Server2", "Server" #Eventually will get from file $a = $Computers.length $User = Read-Host "Enter Username" $Cred = Get-Credential $User cls $ComputerInfo = @{NAME = 1..$a; IP_ADDR = 1..$a; MAC_ADDR = 1..$a} $i = 0 ForEach ($Computer in $Computers) { $wmiquery = get-wmiobject win32_networkadapterconfiguration -computer $Computer -filter "IPEnabled='True'" -Credential $Cred $ComputerInfo.NAME[$i] = $Computer $ComputerInfo.IP_ADDR[$i] = $wmiquery.IPAddress[0] $ComputerInfo.MAC_ADDR[$i] = $wmiquery.MACAddress $i++ } 

上面的代码为我提供了我想要的信息。 但是,我无法导出到csv文件/在表中显示。 如果我只是input: $ComputerInfo 。 我得到:

名称值

MAC_ADDR {MAC1,MAC2,MAC3}

IP_ADDR {IP1,IP2,IP3}

名称{Server1,Server2,Server3}

不完全是我在找什么。 我想要更多的东西:

名称IP_ADDR MAC_ADDR

[值] [值] [值]

[值] [值] [值]

[值] [值] [值]

如果我将$ComputerInfo导出到CSV文件,它会变得更加愚蠢。 我明白了

TYPE System.Collections.Hashtable“IsReadOnly”,“IsFixedSize”,“IsSynchronized”,“Keys”,“Values”,“SyncRoot”,“Count”“False”,“False”,“False”,“System.Collections。哈希表+ KeyCollection”, “System.Collections.Hashtable + ValueCollection”, “System.Object的”, “3”

总的来说,我会在下面做出以下调整。 我改变了一些事情:

  1. 由于Get-Credential可以提供消息,因此将您的凭证提示更改为一行
  2. 创build表作为一个psobject ,它使得它更容易使用和引用列来设置值。
  3. 在使用psobject它不需要索引数组(例如使用column[0]
  4. 我在testing中添加了如果计算机在networking上,然后尝试连接以获取信息(只是良好的做法)。

当你想添加更多的列到你的表中,只需展开你的列的$propsvariables,并填充到你的foreach循环。

我的本地计算机只输出这个脚本: 在这里输入图像说明 在这里输入图像说明

然后只显示它将输出什么,如果我只是ConvertTo-Csv在这里输入图像说明

 $UserCred = (Get-Credential -Message "Enter username") $props = [ordered]@{NAME="";IP_ADDR="";MAC_ADDR=""} $ComputerInfo = New-Object psobject -property $props ForEach ($Computer in $Computers) { if (Test-Connection $computer) { $wmiquery = get-wmiobject win32_networkadapterconfiguration -computer $Computer -filter "IPEnabled='True'" -Credential $Cred $ComputerInfo.NAME = $computer $ComputerInfo.IP_ADDR = $wmiquery.IPAddress[0] $ComputerInfo.MAC_ADDR = $wmiquery.MACAddress } else{ Write-Warning "$($computer) not found on the network" } } $ComputerInfo 

编辑

有一件事,只是补充说,你会看到$computerinfo与我上面的区别是TypeName。 如果你将它传递给Get-Member你的对象将会以System.Collections.Hashtable返回,在那里我将返回一个System.Management.Automation.PSCustomObjectPSCustomObject将返回表中的每个列作为NotePropertytypes,您可以在脚本中使用它(例如,查询计算机信息的域)。

下面的代码做我需要做的事情。 Shawn Melton提供的代码略有修改。 将$ComputerInfo更改$ComputerInfo数组, ForEach更新为将数据添加到$ComputerInfo数组中。

 $Computers = "Server1", "Server2, Server3" $a = $Computers.length $Cred = (Get-Credential) $i=0 $ComputerInfo = 1..$a $props = @{NAME = ""; IP_ADDR = ""; MAC_ADDR = ""} ForEach ($Computer in $Computers) { $ComputerInfo[$i] = New-Object psobject -property $props $wmiquery = get-wmiobject win32_networkadapterconfiguration -computer $Computer -filter "IPEnabled='True'" -Credential $Cred $ComputerInfo[$i].NAME = $computer $ComputerInfo[$i].IP_ADDR = $wmiquery.IPAddress[0] $ComputerInfo[$i].MAC_ADDR = $wmiquery.MACAddress $i++ } $ComputerInfo