PowerShell Экспорт в CSV из ForEach - PullRequest
       2

PowerShell Экспорт в CSV из ForEach

0 голосов
/ 22 октября 2018

Извините, но я не силен в PowerShell (версия 5), как хочу.Я играл с множеством решений, найденных на этом сайте, но не наткнулся на решение для этого кода.В основном, этот код работает и предоставляет результаты, которые мне нужны (просмотр с помощью write-host), но мне нужно получить его для передачи в файл 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 голосов
/ 22 октября 2018

объявляйте пустой объект перед 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
0 голосов
/ 22 октября 2018

Вы можете попробовать заменить:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...