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

l3zydbqr  于 4个月前  发布在  Shell
关注(0)|答案(1)|浏览(63)

我正在使用一个Powershell脚本,它使用Microsoft Graph API SDK来创建一个CSV,然后将该CSV放入“C:\temp”。
列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:\temp中创建的CSV为空。

ulydmbyx

ulydmbyx1#

你的代码的问题是,你可以在一个语言关键字后进行管道传输,在这种情况下,foreach,要修复你的代码,你需要首先从你的循环中捕获所有输出,然后将其管道传输到Export-Csv

# capture output in `$result`
$result = foreach ($user in $usersWithLicenses) {
    [PSCustomObject]@{
        DisplayName                = $user.DisplayName
        LastPasswordChangeDateTime = if ($user.PasswordProfile.LastPasswordChangeDateTime) {
            $user.PasswordProfile.LastPasswordChangeDateTime
        }
        else {
            'N/A'
        }
    }
}

# 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


另外,只要在查询中包含-ConsistencyLevel eventual-CountVariable以启用advanced query capabilities,就应该能够使用OData过滤器assignedLicenses/$count ne 0替换$_.AssignedLicenses.Count -gt 0的过滤器:

$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

相关问题