Powershell从ForEach导出到csv

时间:2018-10-22 15:36:51

标签: powershell

请原谅我,但是我不想要PowerShell(版本5)。我已经在该网站上找到了很多解决方案,但并未偶然发现此代码的解决方案。基本上,这段代码可以工作并提供我需要的结果(通过写入主机查看),但我需要将此结果放入带有标题行的CSV文件中。

任何帮助将不胜感激(为此花了更多的时间超出我的意愿……)

我的代码不变:

# Input File to test from
$csvFile = 'c:\temp\20181013.csv' 
# Read the file   
$computers =import-csv $csvFile
# Process the file
ForEach ($computer in $computers) 
{
$Workstation_Name = $($Computer.Workstation_Name)   #Read the workstation name from the file
$Logon_Duration = $($Computer.Logon_Duration)       #Read the logon duration from the file
$cmp = get-adcomputer -identity $Workstation_Name -Properties Location  #Query Active Directory and get the location field
$Start = $cmp.Location.IndexOf(" ") #Extract the building number from the location field which is between the Bldg:  and ; 
$End = $cmp.Location.IndexOf(";")
$Bldg = $cmp.location.Substring($Start, $End - $Start)  #Extract just the building number
Write-Host $Workstation_Name, $Bldg, $Logon_Duration        #Write the Workstation name, Building number and logon duration
} 

结果如下:

System1  12345 82
Sales1  12345 190
Sales2  123 40
System2  23456 136
…

需要看起来像(在csv文件中)

Workstation_Name, Bldg, Duration
System1, 12345, 82
Sales1, 12345, 190
Sales2, 123, 40
System2, 23456, 136
…

2 个答案:

答案 0 :(得分:1)

您可以尝试替换:

Write-Host $Workstation_Name, $Bldg, $Logon_Duration

作者

$obj = [PSCustomObject]@{"Workstation_Name"= $Workstation_Name; "Bldg"=$Bldg; "Duration"=$Logon_Duration}
$obj | export-csv -Path " 'c:\temp\final.csv' -Append

答案 1 :(得分:1)

在foreach之前声明一个空对象,然后将其填充到循环中,如下所示:

$outputObject = @()

ForEach ($computer in $computers) {

    $itemline = "" | select "Workstation_Name", "Bldg", "Duration"
    $itemline.Workstation_Name = $($Computer.Workstation_Name)
    $itemline.Duration = $($Computer.Logon_Duration)
    $itemline.Bldg = ...

    $outputObject += $itemline 
} 
$outputObject | Export-Csv -Path C:\temp\example.csv -NoTypeInformation