如何通过Powershell从Teams导出的csv文件中获取samAccountName

How to get the samAccountName from a csv file exported from Teams via powershell

我已经从Microsoft Teams导出了CSV文件,并在运行以下命令后获得了所需的数据:

1
2
3
4
5
Import-Csv -Path"C:\\TeamsUserActivity.csv" |
Where-Object { $PSItem.DisplayName -notlike"*-*" } |
Select-Object -Property DisplayName,'LastActivity (UTC Time)' |
Sort-Object -Property 'LastActivity (UTC Time)' -Descending |
Export-Csv -Path"C:\\TeamsUsers.csv"

这将显示以下内容:

1
2
3
4
5
6
7
8
DisplayName        LastActivity (UTC Time)
-----------        -----------------------
Tom Smith          2020-04-16T01:00:47Z
Joe Bloggs         2020-04-16T01:00:47Z
Harry Briggs       2020-04-16T01:00:47Z
Jeff Kerry         2020-04-16T01:00:47Z
Jane Briggs        2020-04-15T23:17:29Z
Betty Smith        2020-04-06T02:56:51Z

我需要删除" LastActivity(UTC Time)"下的第一个日期以下的记录
以下任何内容:2020-04-16
然后在Active Directory上运行Get-ADUser命令以获取每个记录的samAccountName并将其放入第三列。

1
2
3
4
5
6
DisplayName        LastActivity (UTC Time)       UserID
-----------        -----------------------       ------
Tom Smith          2020-04-16T01:00:47Z          tsmith
Joe Bloggs         2020-04-16T01:00:47Z          jbloggs
Harry Briggs       2020-04-16T01:00:47Z          hbloggs
Jeff Kerry         2020-04-16T01:00:47Z          jkerry

曾经测试过从ActiveDirectory到Get-ADUser的一整套方法以返回samaccountname,当我使用静态文本时,该方法仅适用于一条记录

1
Get-ADUser -filter { DisplayName -eq 'Tom Smith' } | Select samAccountName

当我导入csv文件并为每一行运行一个foreach循环时,不是这样。
我测试过的代码应该返回以下内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$in_file ="C:\\PS\\SessionData\\sessionTMSct.csv"
$out_file ="C:\\PS\\SessionData\\sessionTMSctout.csv"

$out_data = @()

ForEach ($row in (Import-Csv $in_file)) {
    If ($row.DisplayName) {
        $out_data += Get-ADUser $row.DisplayName -Properties samAccountName
    }
}

$out_data |
Select DisplayName,'LastActivity (UTC Time)',SamAccountName |
Export-Csv -Path $out_file -NoTypeInformation

以以下错误结尾,前一行:

1
2
3
4
5
6
Get-ADUser : The term 'Get-ADUser' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:8 char:22
+         $out_data += Get-ADUser $row.DisplayName -Properties samAccou ...
+                      ~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Get-ADUser:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException


你快到了。您需要一个自定义字段:

1
2
3
4
5
6
Import-Csv -Path"C:\\TeamsUserActivity.csv" | `
Where-Object { $PSItem.DisplayName -notlike"*-*" } | `
Select-Object -Property DisplayName,'LastActivity (UTC Time)',`
@{l="samAccountName";e={$DN = $_.DisplayName; `
(Get-ADUser -filter {DisplayName -eq $DN}).samAccountName}} | `
Export-CSV -path"C:\\ExportedTeamsUserActivity.csv"