我需要向利用 Miscrosoft Graph SDK 模块的 powershell 脚本添加一个过滤器

问题描述 投票:0回答:1

我正在使用 Powershell 脚本,该脚本使用 Microsoft Graph API SDK 创建 CSV,然后将该 CSV 放入“C: emp”中。 CSV 包含两列。

第 1 列。我们所有的本地 AD 和 Azure AD 用户显示名称。 第 2 列。上次更改密码的时间戳。

我想过滤掉任何未经许可的用户 AKA 资源,例如共享邮箱等。

如果可能的话,如果能够添加第三列也可以标记它们是本地部署还是 AzureAD,那就太好了。这并不像过滤资源那么重要,但也很好。

我创建 2 列 CSV 的原始脚本按预期工作:

Get-MgUser -All | select DisplayName,lastPasswordChangeDateTime | Export-Csv "C:\temp\userupdate" 

我尝试在开头添加一个过滤器来替换-All:

-Filter 'assignedLicenses/$count eq 0'B'

但事实证明您不能将声明的变量用于过滤器。所以我想如果我要开始声明变量,我会尝试添加第三列并过滤掉资源并使用此脚本:

$usersWithLicenses = Get-MgUser -All | Where-Object { $_.AssignedLicenses.Count -gt 0 }

foreach ($user in $usersWithLicenses) {
    [PSCustomObject]@{
        DisplayName = $user.DisplayName
        LastPasswordChangeDateTime = if ($user.PasswordProfile.LastPasswordChangeDateTime) { $user.PasswordProfile.LastPasswordChangeDateTime } else { "N/A" }
    }
} | Export-Csv -Path "C:\temp\userupdate.csv"

此脚本没有抛出任何错误,但它在 C: emp 中创建的 CSV 是空白的。

powershell azure-active-directory active-directory microsoft-graph-sdks
1个回答
0
投票

您的代码的问题是,您可以在 语言关键字(在本例中为

foreach
)之后进行管道传输,要修复您的代码,您需要首先捕获循环中的所有输出,然后将其通过管道传输到
Export-Csv

# capture output in `$result`
$result = foreach ($user in $usersWithLicenses) {
    # same code goes here
}

# pipe here
$result | Export-Csv -Path 'C:\temp\userupdate.csv' -NoTypeInformation

或者,您可以将循环更改为

ForEach-Object
(将
$user
更改为
$_
以引用枚举项),然后您可以将其输出直接通过管道传输到
Export-Csv
:

Get-MgUser -Filter -All |
    Where-Object { $_.AssignedLicenses.Count -gt 0 } |
    ForEach-Object {
        [PSCustomObject]@{
            DisplayName                = $_.DisplayName
            LastPasswordChangeDateTime = if ($_.PasswordProfile.LastPasswordChangeDateTime) {
                $_.PasswordProfile.LastPasswordChangeDateTime
            }
            else {
                'N/A'
            }
        }
    } |
    Export-Csv 'C:\temp\userupdate.csv' -NoTypeInformation

顺便说一句,只要您在查询中包含

$_.AssignedLicenses.Count -gt 0
assignedLicenses/$count ne 0
以启用
高级查询功能
,您就应该能够使用 OData 过滤器 
-ConsistencyLevel eventual 替换 -CountVariable

的过滤器
$getMgUserSplat = @{
    Filter           = 'assignedLicenses/$count ne 0'
    CountVariable    = 'count'
    ConsistencyLevel = 'eventual'
    All              = $true
}

$expression = {
    if ($_.PasswordProfile.LastPasswordChangeDateTime) {
        return $_.PasswordProfile.LastPasswordChangeDateTime
    }

    'N/A'
}

Get-MgUser @getMgUserSplat |
    Select-Object DisplayName, @{ N = 'LastPasswordChangeDateTime'; E = $expression } |
    Export-Csv 'C:\temp\userupdate.csv' -NoTypeInformation
© www.soinside.com 2019 - 2024. All rights reserved.