[英]Arranging output to CSV from Powershell foreach loop
I am writing a powershell function which executes a foreach loop. 我正在写一个执行foreach循环的powershell函数。 The loops goes through each server name in a text file list of hosts and then for each one, pulls the free space on C and then assigns it to a variable.
循环遍历主机的文本文件列表中的每个服务器名称,然后为每个服务器名称拉取C上的可用空间,然后将其分配给变量。
Then another loop goes through the list again and gets the name of the hosts and then adds it to a variable. 然后另一个循环再次遍历列表并获取主机的名称,然后将其添加到变量中。
Then I have a variable which takes the two variables containing the data pulled from the loops and export it to CSV. 然后我有一个变量,它接受包含从循环中提取的数据的两个变量并将其导出为CSV。 It puts the correct data in the CSV but I would like to format it in a certain way.
它将正确的数据放入CSV中,但我想以某种方式对其进行格式化。 The current csv output is (for 4 entries for example) 'server 1' 'server2' 'server 3' 'server 4' 'diskspacevalue1' '2' '3' '4' etc.
当前的csv输出是(例如4个条目)'服务器1''服务器2''服务器3''服务器4''diskspacevalue1''2''3''4'等。
So Im at the point where I have all the data I need but I need to arrange it so that one cell has the server name and then the cell next to it has it's respective value. 所以我在我需要的所有数据的位置,但我需要安排它,以便一个单元格具有服务器名称,然后它旁边的单元格具有相应的值。
I have a feeling I should be creating objects or using an array but wondered if there was anything I could add to implement the formatting I want based on the script I have written so far? 我有一种感觉,我应该创建对象或使用数组,但想知道是否有任何我可以根据我到目前为止编写的脚本实现我想要的格式?
function diskcheck {
$freespace = Get-Content C:\temp2\DiskspaceProj\hosts.txt | Foreach-Object {
Get-WmiObject win32_logicaldisk -Computername $_ -Filter "DeviceID='C:'" | select -ExpandProperty "FreeSpace"
}
$hostName = Get-Content C:\temp2\DiskspaceProj\hosts.txt | Foreach-Object {
Get-WmiObject Win32_ComputerSystem -ComputerName $_ | Select -ExpandProperty "Name"
}
$output = "$hostname, $freespace" | echo > C:\temp2\DiskspaceProj\diskspace.csv
}
diskcheck
Don't maintain two separate array - create one array of objects that contain both properties: 不要维护两个单独的数组 - 创建一个包含两个属性的对象数组:
function diskcheck
{
param(
[string]$Path = 'C:\temp2\DiskspaceProj\hosts.txt'
)
Get-Content $Path |ForEach-Object {
New-Object psobject -Property @{
Hostname = Get-WmiObject Win32_ComputerSystem -ComputerName $_ |Select -ExpandProperty Name
FreeSpace = Get-WmiObject win32_logicaldisk -Computername $_ -Filter "DeviceID='C:'" | select -ExpandProperty FreeSpace
}
}
}
Then use Export-CSV
to export the list to a file: 然后使用
Export-CSV
将列表导出到文件:
diskcheck |Select Hostname,FreeSpace |Export-Csv C:\diskspace_output.csv -NoTypeInformation
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.