【问题标题】:Foreach loop to get department name in powershell office365Foreach 循环在 powershell office365 中获取部门名称
【发布时间】:2019-09-03 17:28:15
【问题描述】:

我正在尝试从 UserPrincipalNames 列表中获取部门

我可以让它为 foreach 循环之外的单个用户工作。它在我遇到问题的地方添加了循环。

Connect-MsolService
$users = Import-Csv C:\Users\me\Desktop\users.csv

foreach ($user in $users){

Get-MsolUser -UserPrincipalName $user | Select-Object firstname, lastname, UserPrincipalName, department |Export-Csv C:\Users\me\Desktop\test.csv

}

CSV 中列出了 50 个电子邮件地址,每行一个电子邮件地址。第一行是“UserPrincipalName”

CSV 样本数据

userprincipalname
useremail1@mydomain.com
useremail2@mydomain.com
useremail3@mydomain.com
useremail4@mydomain.com

【问题讨论】:

  • 什么不起作用?我完全尝试了您的示例,它按预期返回了结果。请提供任何错误消息或解释您的预期与结果。
  • 呈现的代码不会将所有具有必要信息的用户发送到目标 TEST.CSV。 (实际上,CSV 将是空的,并带有给定的代码。)请参阅下面的答案。
  • 你没有给 Export-Csv 任何可导出的东西
  • 是的,export-csv 放错了地方,但即使没有它,我也会收到错误 Get-MsolUser : User Not Found. User: @{UserPrincipalName=user@test.com}
  • 您正在使用 $user 作为您的 UPN ...但这来自导入 CSV。这意味着它将是一个具有至少一个属性的对象,该属性具有至少一个值。如果你使用$User.PropertyNameThatContainsTheUPN会发生什么?

标签: powershell foreach office365


【解决方案1】:

想想 PowerShell - 管道使用对象,你有一个 ForEach-Object cmdlet:

Connect-MSOLService

Import-CSV -Path C:\Users\Me\Desktop\Users.CSV | 
    ForEach-Object { Get-MSOLUser -UserPrincipalName $_.UserPrincipalName | 
        Select-Object firstname, lastname, UserPrincipalName, department } | 
    Export-CSV C:\Users\Me\Desktop\test.CSV

【讨论】:

  • 这样我得到了错误Get-MsolUser : Cannot bind argument to parameter 'UserPrincipalName' because it is null
  • 您的 CSV 文件有问题。如果其中包含有效数据,并且格式正确,则$_ 不可能为空。
  • 我已经更新了这个问题。我更改了我的 CSV,为第一行提供了 UserPrincipalName 的标题,现在我收到了 Get-MSOLUser : User Not Found. User: @{UserPrincipalName=useremail@mydomain.com}. At line:5 char:19 + ForEach-Object { Get-MSOLUser -UserPrincipalName $_ | 的先前错误。我已经运行get-msoluser -UserPricipalName useremail@mydomain.com 只是为了确定电子邮件地址在那里并且我确实得到了结果
  • 我想通了。我没有正确键入其中一行。我猜阅读很难
【解决方案2】:

如果您需要从 csv 查找数据,然后想在脚本中使用它们并将 scrip 的结果导出到另一个 CSV

# Importing MsOnline Module           
Import-Module MSOnline
Connect-MsolService


#Import excel document containing our data ,Path "C:\list-email.csv" 
$ImportData = Import-Csv "C:\list-email.csv"

$Output = foreach ( $Data in  $ImportData )
{
    #Storing Email column data in $Data for each row
    write-host $Data.Email
        
    Get-MsolUser -UserPrincipalName $Data.IONEmail | Select-Object UserPrincipalName,LastPasswordChangeTimestamp, Departement
}
#Output the array to the CSV File
$Output | Export-CSV "C:\LastLogonDateExport.csv"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-24
    • 2021-01-26
    • 2021-07-23
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    • 2019-09-19
    相关资源
    最近更新 更多