[英]exporting results of powershell script to csv
I need some help, I have a small script which updates AD attributes from a.csv file however I want to export the results of the updates so I can check if its updated all users successfully or if there are any failures (ie it failed to find the user.).我需要一些帮助,我有一个小脚本,它从 a.csv 文件更新 AD 属性但是我想导出更新的结果,以便我可以检查它是否成功更新了所有用户或是否有任何失败(即它未能找到用户。)。
Does anyone know how I can do this please?请问有谁知道我该怎么做?
This is the current script I have这是我当前的脚本
###UPDATE DEPARTMENT, DIVISION, JOB TITLE
$Users = Import-CSV C:\Users\Documents\CurrentWork\test.csv
ForEach ($User in $Users) {
Get-ADUser -Filter * -property displayname | where {$_.displayname -eq $User.EmployeeFullName} | Set-ADUser -department $User.Department -Division $User.Division -Title $User.JobTitle
}
###UPDATE INFO ATTRIBUTE, DEPARTMENT NUMBER
$Users = Import-CSV C:\Users\Documents\CurrentWork\test.csv
ForEach ($User in $Users) {
Get-ADUser -Filter * -property displayname | where {$_.displayname -eq $User.EmployeeFullName} | Set-ADUser -Replace @{info=$User.Service;departmentNumber=$User.'Cost Centre'}
}
The most flexible way to solve a problem like this is to create an empty obejct array, fill it with new custom objects, and then export the object array to csv.解决此类问题最灵活的方法是创建一个空的对象数组,用新的自定义对象填充它,然后将 object 数组导出到 csv。
In pseudo-code, it looks like this:在伪代码中,它看起来像这样:
[array]$outputObjects = $null
foreach ($myVar in $myObjects) {
[array]$outputObjects += [PSCustomObject]@{
PropertyName1 = "Value1"
PropertyName2 = "Value2"
}
}
$outputObjects | Export-Csv -Path "C:\myFile.csv" -Encoding UTF8 -NoTypeInformation
In your example, you could use this approach like this:在您的示例中,您可以像这样使用这种方法:
[array]$outputObjects = $null
ForEach ($User in $Users) {
$adUser = Get-ADUser -Filter * -Property DisplayName,Department,Division,Title,info,departmentNumber | Where-Object {$_.DisplayName -eq $User.EmployeeFullName}
[array]$outputObjects += [PSCustomObject]@{
UserPrincipalName = $adUser.UserPrincipalName
DisplayName = $adUser.DisplayName
Department = $adUser.Department
Division = $adUser.Division
Title = $adUser.Title
info = $adUser.info
departmentNumber = $adUser.departmentNumber
}
}
$outputObjects | Export-Csv -Path "C:\Users\Documents\CurrentWork\exportedADUserData.csv" -Encoding UTF8 -NoTypeInformation
Even faster, but only noticeable if you have a bigger amount of objects (~10'000+):更快,但只有当你有更多的对象(~10'000+)时才会注意到:
$outputObjects = foreach ($myVar in $myObjects) {
[PSCustomObject]@{
PropertyName1 = "Value1"
PropertyName2 = "Value2"
}
}
$outputObjects | Export-Csv -Path "C:\myFile.csv" -Encoding UTF8 -NoTypeInformation
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.