当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] Get-MgUser:如何使用 PowerShell 获取 Azure AD 用户

作者:精品下载站 日期:2024-12-14 03:42:22 浏览:14 分类:玩电脑

Get-MgUser:如何使用 PowerShell 获取 Azure AD 用户


从 2022 年 12 月开始,我们将需要使用 Get MgUser cmdlet 来获取并导出我们的 Azure AD 用户。 Get-MgUser 是适用于 PowerShell 的 Microsoft Graph SDK 的一部分。它允许我们通过单个端点与所有 Microsoft 服务进行交互。

Microsoft 365 租户中的所有用户帐户都存储在 Azure Active Directory 中。我们可以通过管理中心或Azure Portal来管理它们,但有时PowerShell更方便。

在本文中,我将解释如何使用 Get MgUser cmdlet 从 Azure AD 查找和检索用户信息。我还创建了一个完整的脚本,允许您将所有用户导出到 CSV,您可以在本文末尾找到该脚本。

开始使用 Get-MgUser

在开始之前,请确保您已在 PowerShell 中安装了 Microsoft Graph 模块。在本文中,您可以找到有关如何安装该模块的完整指南。但要简单地安装模块,请使用以下命令:

Install-Module Microsoft.Graph -Force

Get-MgUser cmdlet 允许您从 Azure Active Directory 查找并提取用户信息。我们可以使用几个参数来查找或过滤用户:

  • UserId - 根据 UPN 或 ObjectID 返回特定用户
  • 过滤 - 基于 oDate v3 查询检索多个对象
  • 搜索 - 获取与searchString匹配的所有用户
  • Top - 返回 n 个结果
  • 全部 - 返回所有结果(默认情况下返回前 100 项)

很高兴知道该 cmdlet 默认情况下仅返回前 100 个结果。因此,请确保在需要时使用 -all 参数来获取所有结果。

第一步是将 Microsoft Graph 连接到正确的范围。我们仅要检索用户数据,因此可以使用 User.Read.All 范围。

Connect-MgGraph -Scopes 'User.Read.All'

要测试 cmdlet 是否正常工作,您只需使用以下 cmdlet 从 Azure Active Directory 获取所有用户:

Get-MgUser -All

[玩转系统] Get-MgUser:如何使用 PowerShell 获取 Azure AD 用户

要获取单个用户,我们可以使用用户的 UserId。这可以是用户的 UserPrincipalName 或实际的用户 ID:

# Get the user by the UserPrincipalName
Get-MgUser -UserId [email protected]

# Get the user by the actual id:
Get-MgUser -UserId 7a3b301d-0462-41b6-8468-19a3837b8ad1

建议

您现在还可以使用 Microsoft Entra PowerShell 模块管理您的用户。在本文中阅读有关此新模块的更多信息。

将过滤器与 Get-MgUser 一起使用

就像使用 Get-AzureAduser cmdlet 一样,我们可以过滤用户。该过滤器基于 oDate v3 查询,但并非支持所有运算符。我们只能使用以下运算符来过滤到用户:

OperatorDescriptionExampleeqEquals tojobtitle eq ‘Marketing Assistant’andAndjobtitle eq ‘Recruiter’ and jobtitle eq ‘hr’orOrjobtitle eq ‘Recruiter’ or jobtitle eq ‘hr’startswithString starts withstartswith(jobtitle,’recr’)

重要的是,将过滤器查询括在双引号中,并将要过滤的字符串括在单引号中。仅当您过滤布尔值时,才不需要在 true 或 false 语句两边加上引号。

那么让我们看一下使用 -filter 参数的几个示例。要通过显示名称查找用户,我们可以指定用户的完整名称或使用 startsWith 运算符。请记住,我们不能在这里使用通配符或 -like 运算符。

# Find the user based on the full name
Get-MgUser -Filter "DisplayName eq 'Adele Vance'"

# Find the user by the first part of the name
Get-MgUser -Filter "startsWith(DisplayName, 'A')"

[玩转系统] Get-MgUser:如何使用 PowerShell 获取 Azure AD 用户

同样的方法也可以用于获取职位为“营销助理”的所有用户,例如:

Get-MgUser -Filter "jobtitle eq 'Marketing Assistant'"

例如,要使用 Get-MgUser cmdlet 仅获取启用的用户帐户,我们可以使用以下命令:

Get-MgUser -Filter 'accountEnabled eq true' -All

请注意,我添加了 -all 参数。默认情况下,Get MgUser cmdlet 仅返回前 100 个结果。通过添加 -all 参数,我们可以获得所有返回的结果。

我们还可以通过在过滤查询中使用 andor 来过滤多个条件:

Get-MgUser -Filter "department eq 'Marketing' and jobtitle eq 'Manager'"

我想分享的另一个例子是获取去年创建的所有用户的选项。为此,我们可以过滤 CreatedDateTime 属性:

Get-MgUser -Filter "CreatedDateTime ge $((Get-Date).AddYears(-1).ToString("s"))Z"

使用搜索来查找用户

除了filter参数之外,我们还可以使用-Search参数来查找用户。该参数需要您要搜索的属性和值。您还需要将 -consistencylevel 设置为 eventual

-search 参数的优点是它允许我们搜索值的任何部分。例如,如果想搜索名称的一部分,我们可以使用:

Get-MgUser -Search 'DisplayName:van' -ConsistencyLevel eventual

[玩转系统] Get-MgUser:如何使用 PowerShell 获取 Azure AD 用户

另请注意,您需要将搜索查询用单引号引起来。您可以对 Get-MgUser cmdlet 返回的几乎所有字段使用搜索参数。

在 Get MgUser 中结合搜索和过滤

我们还可以将 -search 和 -filter 参数组合在一个命令中。这允许我们仅在启用的帐户中搜索姓名或职位,例如:

Get-MgUser -Filter 'accountEnabled eq true' -Search 'DisplayName:van' -ConsistencyLevel eventual

选择要返回的属性

使用 Get-MgUser cmdlet 时,您可能已经注意到它默认情况下不会返回很多属性。大多数字段为空或包含值 Microsoft.Graph.PowerShell.Models.,后跟实体名称。那么我们如何检索这些数据呢?

[玩转系统] Get-MgUser:如何使用 PowerShell 获取 Azure AD 用户

我们可以使用两个参数来获取所需的信息,-property-expandproperty。

-property 参数就像我们可以在 cmdlet 后面通过管道传输的 select 参数一样。唯一的区别是,使用 select 时,所有数据均由 Microsoft Graph 返回并在 PowerShell 中过滤掉。

Get-MgUser -UserId [email protected] | Select DisplayName,BusinessPhones,Mail,JobTitle

DisplayName BusinessPhone     Mail                           JobTitle
----------- -------------     ----                           --------
Adele Vance {+1 425 555 0109} [email protected] Retail Manager

当您使用属性参数时,Microsoft Graph 仅返回您需要的数据。特别是在处理大量记录时,这比使用 select 更快。

Get-MgUser -UserId [email protected] -Property DisplayName,BusinessPhones,Mail,JobTitle | fl

如果将结果输出到列表,您将看到只有使用属性参数选择的字段包含数据。

扩展 Microsoft.Graph.PowerShell.Models

查看用户的属性时,您可能已经注意到其中一些属性包含值 Microsoft.Graph.PowerShell.Models,后跟资源名称。这些模型(或资源)是您正在查看的资源类型的关系。

这些关系应该可以让我们轻松查看资源的相关数据。如果我们选择用户,我们可能想知道它的管理者。

为此,我们需要扩展属性并选择管理器对象的正确参数:

Get-MgUser -UserId [email protected] -ExpandProperty manager | Select @{Name = 'Manager'; Expression = {$_.Manager.AdditionalProperties.displayName}}

# Result:
Manager
-------
Miriam Graham

这些关系的挑战是找到您需要的正确字段和权限。我们现在仅使用 User.Read.All 范围连接到 Microsoft Graph。例如,如果我们想要在邮箱设置中查看用户的工作时间,那么我们首先需要找到正确的范围并将其添加到我们的会话中。

为了找到正确的权限,我喜欢使用 Rest API 文档。如果展开资源,它将显示资源的关系。然后,您可以单击类型,这将带您进入相关资源,您可以在其中找到所需的权限。

因此,对于邮箱设置,我们需要添加 MailboxSettings.Read 权限:

Connect-MgGraph -Scopes "User.Read.All","MailboxSettings.Read"

然后我们可以选择属性和嵌套值:

Get-MgUser -UserId [email protected] -Property MailboxSettings | Select @{Name = 'days'; Expression = {$_.MailboxSettings.WorkingHours.DaysofWeek}}

用于获取所有 Azure AD 用户并导出到 CSV 的脚本

我创建了一个完整的脚本,允许您获取所有 Azure Active Directory 用户并将其导出到 CSV 文件。运行脚本时有几个选项:

  • 获取用户的管理员 - 默认 True
  • 获取启用、禁用或两个用户帐户 - 默认 True
  • 设置 CSV 文件的导出路径 - 默认情况下脚本的位置

您可以从我的 GitHub 存储库下载该脚本的最新版本。要运行脚本,只需导航到脚本位置并运行:

.\Get-MgUsers.ps1 -path c:\temp\users.csv

如果您想了解有关如何运行脚本或如何将脚本位置添加到 PowerShell 配置文件的更多信息,请务必阅读本文。

param(
  [Parameter(
    Mandatory = $false,
    HelpMessage = "Get the users manager"
  )]
  [switch]$getManager = $true,

  [Parameter(
    Mandatory = $false,
    HelpMessage = "Get accounts that are enabled, disabled or both"
  )]
    [ValidateSet("true", "false", "both")]
  [string]$enabled = "true",

  [Parameter(
    Mandatory = $false,
    HelpMessage = "Enter path to save the CSV file"
  )]
  [string]$path = ".\ADUsers-$((Get-Date -format "MMM-dd-yyyy").ToString()).csv"
)


Function Get-Users {
    <#
    .SYNOPSIS
      Get users from the requested DN
    #>
    process{
      # Set the properties to retrieve
      $properties = @(
        'id',
        'DisplayName',
        'userprincipalname',
        'mail',
        'jobtitle',
        'department',
        'OfficeLocation',
        'MobilePhone',
        'BusinessPhones',
        'streetAddress',
        'city',
        'postalcode',
        'state',
        'country',
        'AccountEnabled',
        'CreatedDateTime'
      )

      If (($getManager.IsPresent)) {
        # Adding additional properties for the manager
        $select = $properties += @{Name = 'Manager'; Expression = {$_.Manager.AdditionalProperties.displayName}}
        $select += @{Name ="Phone"; Expression = {$_.BusinessPhones}} 
      }else{
        $select = $properties
      }

      # Get enabled, disabled or both users
      switch ($enabled)
      {
        "true" {$filter = 'AccountEnabled eq true'}
        "false" {$filter = 'AccountEnabled eq false'}
        "both" {$filter = ''}
      }

      # Get the users
      Get-MgUser -Filter $filter -Property $properties -ExpandProperty Manager | select $select
    }
}


Function Get-AllMgUsers {
  <#
    .SYNOPSIS
      Get all AD users
  #>
  process {
    Write-Host "Collecting users" -ForegroundColor Cyan

    # Collect and loop through all users
    Get-Users | ForEach {

      [pscustomobject]@{
        "Name" = $_.DisplayName
        "UserPrincipalName" = $_.UserPrincipalName
        "Emailaddress" = $_.mail
        "Job title" = $_.JobTitle
        "Manager" = $_.Manager
        "Department" = $_.Department
        "Office" = $_.OfficeLocation
        "Phone" = $_.Phone
        "Mobile" = $_.MobilePhone
        "Enabled" = if ($_.AccountEnabled) {"enabled"} else {"disabled"}
        "Street" = $_.StreetAddress
        "City" = $_.City
        "Postal code" = $_.PostalCode
        "State" = $_.State
        "Country" = $_.Country
        "Account Created on" = $_.CreatedDateTime
      }
    }
  }
}

# Check if MS Graph module is installed
if (Get-InstalledModule Microsoft.Graph) {
  # Connect to MS Graph
  Connect-MgGraph -Scopes "User.Read.All"
}else{
  Write-Host "Microsoft Graph module not found - please install it" -ForegroundColor Black -BackgroundColor Yellow
  exit
}

Get-AllMgUsers | Sort-Object Name | Export-CSV -Path $path -NoTypeInformation

if ((Get-Item $path).Length -gt 0) {
  Write-Host "Report finished and saved in $path" -ForegroundColor Green

  # Open the CSV file
  Invoke-Item $path

}else{
  Write-Host "Failed to create report" -ForegroundColor Red
}

总结

适用于 PowerShell 的 Microsoft Graph SDK 仍然很新,在撰写本文时还没有很好的文档记录。因此,找到正确的语法或 cmdlet 来获取所需的信息可能有点困难。

我希望本文可以帮助您开始使用 Get-MgUser cmdlet。如果您有任何疑问,请在下面的评论中告诉我。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯