我运行一个用于日历委派的所有用户命令。然后我报告。问题是如何包括没有日历授权的人?(代码如下)
在这一行If ($null -ne $DelegateCal)中,我确保某人有日历委托,然后构建对象。
如果我不使用+=,那么当我为$null添加一个Else时,我不确定如何构建对象
<#All Google Calendar delegate report#>
# filename function
Import-Module C:\tasks\Modules\MRNAP\MRNAP.psm1
$AllGoogleUsers = gam print users fields suspended | ConvertFrom-Csv | Where-Object { $_.suspended -eq $False } | Select-Object -ExpandProperty PrimaryEmail
ForEach ($UserEmail in $AllGoogleUsers) {
$DelegateCal = gam calendar $UserEmail print acls | convertfrom-csv | Where-Object { $_.'scope.type' -eq 'user' -and $_.'Scope.value' -ne $UserEmail } -ErrorAction SilentlyContinue
If ($null -ne $DelegateCal) {
$CalendarDelegateList = foreach ($line in $DelegateCal) {
[PSCustomObject]@{
Owner = $line.calendarId
Type = 'Calendar'
Delegate = $line.'scope.value'
Role = $line.role
}
}
}
}
$CalendarDelegateList = $CalendarDelegateList | Sort-Object -Property Owner
$filename = MRNAP -ReportName WhoIsCalendarDelegated -Move
$CalendarDelegateLis | Export-Csv $filename -NoTypeInformation | Format-Table text-align=left -AutoSize这就是我用+=做的
$AllGoogleUsers = gam print users fields suspended | ConvertFrom-Csv | Where-Object { $_.suspended -eq $False } | Select-Object -ExpandProperty PrimaryEmail
ForEach ($UserEmail in $AllGoogleUsers) {
$DelegateCal = gam calendar $UserEmail print acls | convertfrom-csv | Where-Object { $_.'scope.type' -eq 'user' -and $_.'Scope.value' -ne $UserEmail } -ErrorAction SilentlyContinue
If ($null -ne $DelegateCal) {
foreach ($line in $DelegateCal) {
$CalendarDelegateList += [PSCustomObject]@{
Owner = $UserEmail
Type = 'Calendar'
Delegate = $line.'scope.value'
Role = $line.role
}
}
}
Else {
$CalendarDelegateList += [PSCustomObject]@{
Owner = $UserEmail
Type = 'Calendar'
Delegate = 'None'
Role = 'None'
}
}
}发布于 2021-09-15 16:36:51
总是希望让 PowerShell 为您收集数组中的语句输出,而不是手动构建输出列表--为了简洁和性能;有关更多信息,请参见this answer。
这甚至适用于嵌套的foreach循环,就像在您的例子中一样。
应用于您的场景(节略):
[array] $CalendarDelegateList =
foreach ($UserEmail in $AllGoogleUsers) {
$DelegateCal = gam calendar $UserEmail print acls | ConvertFrom-Csv | Where-Object { $_.'scope.type' -eq 'user' -and $_.'Scope.value' -ne $UserEmail } -ErrorAction SilentlyContinue
If ($null -ne $DelegateCal) {
foreach ($line in $DelegateCal) {
# Construct *and ouput* a [pscustomobject] instance.
[PSCustomObject]@{
Owner = $UserEmail
# ...
}
}
}
Else {
[PSCustomObject]@{
Owner = $UserEmail
# ...
}
}
}来自foreach循环内部的所有foreach实例(隐式)输出(无论是直接的还是嵌套的)都自动收集在变量$CalendarDelegateList中。
注意:
具有来自循环的两个或多个输出对象的[object[]]).
$CalendarDelegateList变量接收一个常规的PowerShell数组(类型为PowerShell)[array]类型约束(缩写为:[object[]])还可以确保结果是一个数组,即使循环只输出一个对象。https://stackoverflow.com/questions/69196509
复制相似问题