函数和 ForEach 循环,需要将 `Measure-Object` 结果相加

问题描述

所以这个庞大的脚本我已经用了将近一个月的时间在你们这里​​了不起的人的大量帮助下......我快完成了。我正在尝试计算 ForEach 循环中 Measure-Object 调用的结果。基本上我想在脚本运行结束时显示所有管理器的 DirectReports 总数。喜欢:"$AddUserCount new users added to groups"

这里是整个背景脚本:

#---------------------------------------------------------[Initializations]-------------------------------------------------------- 
 Param (
[Parameter(Mandatory=$false)]
[Switch]$logonly
)

#  Dot Source required Function Libraries
#. "\\server\e$\scripts\Logging_Functions.ps1" 
. "c:\users\documents\powershell\Functions\Logging_Functions.ps1"

#  Error Action
$ErrorActionPreference = 'silentlycontinue'
#  Debug preference
$global:DebugPreference = "continue"
#  WhatIf Preference,uncomment to run script in a logging only function
#$WhatIfPreference = $true

#----------------------------------------------------------[Declarations]----------------------------------------------------------
  
#  Script Version
$sScriptVersion = "1.0"

Import-Module ActiveDirectory


#  Log File Info
$sLogPath = "C:\Users\Documents\powershell\Logs"
#$sLogPath = "\\server\e$\Logs"
$sLogName = "Set-LitmosGroups_$(get-date -f yyyy-MM-dd_HH-mm-ss).log"
$slogonlyPath = "C:\Users\Documents\powershell\Logs"
$slogonlyName = "\Set-LitmosGroups (Log Only)_$(get-date -f yyyy-MM-dd_HH-mm-ss).log"
$sLogFile = Join-Path -Path $sLogPath -Childpath $sLogName
$slogonlyFile = Join-Path -Path $slogonlyPath -Childpath $slogonlyName
$LogLine = $null 

#$logonly = $null

#  Variable Initializations
#  Org Unit where the target groups reside (Litmos)
$OU = "ou=test_litmos,ou=test accounts,ou=domain,dc=net"
#  Org unt containing the All Managers security group
$OU2 = "CN=All Managers,OU=Organizational,OU=Groups,OU=domain,DC=net"

#  Get member of the 'ALL Managers' security group
$Managers = Get-ADGroupMember -identity $OU2 | Select-Object -expandproperty samaccountname

#  Get AD groups with Report to in the name in $ou
$ReportsTo = Get-adgroup -searchbase $ou -filter "Name -like 'Report to *'" |  
Select-Object -expandproperty name

$Samecount = 0
$AddGroupCount = 0
$Addusercount = 0
$LOAddUserCount = 0
$LOGroupCount = 0
$GroupsRemoved = 0
$LOGroupsRemoved = 0

#----------------------------------------------------------[Functions]-------------------------------------------------------------


Function Get-DirectReport {
    #requires -Module ActiveDirectory    
    [CmdletBinding()]
    param(
        [Parameter(
            Mandatory = $false,ValueFromPipeline = $true,ValueFromPipelineByPropertyName = $true
        )]
 
        [string]  $SamAccountName,[switch]  $norecurse
    )
 
    BEGIN {}
 
    PROCESS {
        $UserAccount = Get-ADUser $SamAccountName -Properties DirectReports,displayName
        $UserAccount | select -ExpandProperty DirectReports | ForEach-Object {
            $User = Get-ADUser $_ -Properties DirectReports,displayName,Title,EmployeeID
            if ($null -ne $User.EmployeeID) {
                if (-not $norecurse) {
                    Get-DirectReport $User.SamAccountName
                }
                [PSCustomObject]@{
                    SamAccountName    = $User.SamAccountName
                    UserPrincipalName = $User.UserPrincipalName
                    displayName       = $User.displayName
                    Manager           = $UserAccount.displayName
                }
            }
        }
    }
 
    END {}
 
}

Function New-bhReportToGroup {
    [CmdletBinding(SupportsShouldProcess)] 
    $Log1 = "New group for " + $manager + " has been created."
    $Log2 = "Group for " + $manager + " already exists."
    #From on when you see the below line $script:<variable> that sets the scope for that variable to the entire script which means other functions can use the value
    $script:ReportsTo = $ReportsTo -replace ("Report to ","")
    if ($manager -notin $ReportsTo) { 
        new-adgroup -name "Report to $manager" -groupscope global -path $ou
        $LogLine = $Log1
        $Script:AddGroupCount++
        Log-Write -LogPath $sLogFile -LineValue $LogLine 
    }
    else {
        $LogLine = $Log2
        Log-Write -LogPath $sLogFile -LineValue $LogLine 
    }
}

Function New-bhReportToGroup_logonly {
    [CmdletBinding(SupportsShouldProcess)]
    $Log1 = "New group for " + $manager + " would have been created in $OU."
    $Log2 = "Group for " + $manager + " already exists in $OU."
    $script:ReportsTo = $ReportsTo -replace ("Report to ","")
    if ($manager -notin $ReportsTo) { 
        $Script:LOGroupCount++
        $LogLine = $Log1
        Log-Write -LogPath $slogonlyFile -LineValue $LogLine 
    }
    else {
        $LogLine = $Log2
        Log-Write -LogPath $slogonlyFile -LineValue $LogLine 
    }
}

Function Get-bhDReports {
    [CmdletBinding(SupportsShouldProcess)] 
    $directreports = Get-Directreport $manager -norecurse  | Select-Object samAccountName
    if ($null -ne $directreports) {        
        $LogLine = "Gathering direct reports for $manager"
        Log-Write -LogPath $sLogFile -LineValue $LogLine 
    }
    else {
        $LogLine = "$manager has no reports."
        Log-Write -LogPath $sLogFile -LineValue $LogLine 
    }   
}

Function Set-bhRTGmembers {
    [CmdletBinding(SupportsShouldProcess)] 
    #  Get manager's 'report to <manager>' group again to update members
    $managerReportToGroup = Get-ADGroup -SearchBase $OU -Filter "Name -like 'Report to $Manager'"
    $Script:directreports = Get-Directreport $manager -norecurse  | Select-Object -expand samAccountName
    if ($managerReportToGroup) {
        Add-ADGroupMember -identity $managerReportToGroup.Name -members $DirectReports
        Add-ADGroupMember -identity $managerReportToGroup.name -members $Manager
        $LogLine = "Report to " + $Manager + " updated."
        $Script:AddUserCount++
        Log-Write -LogPath $sLogFile -LineValue $LogLine 
    }
    else {
        $LogLine = "Could not find group for " + $Manager
        Log-Write -LogPath $sLogFile -LineValue $LogLine 
    }
}

Function Set-bhRTGmembers_logonly {
    [CmdletBinding(SupportsShouldProcess)]
    $DirectReports = Get-Directreport $manager -norecurse  | Select-Object -expand samAccountName
    #  Get manager's 'report to <manager>' group again to update members
    $managerReportToGroup = Get-ADGroup -SearchBase $OU -Filter "Name -like 'Report to $Manager'"
    if ($managerReportToGroup) {
        $LogLine = "Report to $Manager would be updated with $DirectReports"
        Log-Write -LogPath $slogonlyFile -LineValue $LogLine 
    }
    else {
        $LogLine = "Group for $Manager not found,would be updated with $DirectReports"
        Log-Write -LogPath $slogonlyFile -LineValue $LogLine 
    }
}

Function Remove-bhOOSGroups {
    [CmdletBinding(SupportsShouldProcess)] 
    $report = $report -replace ("Report to ","")
    if ($Report -notin $managers) {
        Remove-ADGroup -Identity "Report to $Report" -confirm:$false
        $LogLine = $report + " user has fell out of scope,Report group removed."
        $Script:GroupsRemoved++
        Log-Write -LogPath $sLogFile -LineValue $LogLine
    }
    else {
       Continue
    }
}

Function Remove-bhOOSGroups_logonly {
    [CmdletBinding(SupportsShouldProcess)]
    $report = $report -replace ("Report to ","")
    if ($Report -notin $managers) {
        $LogLine = $report + " user has fell out of scope,Report group would be removed."
        $Script:LOGroupsRemoved++
        Log-Write -LogPath $slogonlyFile -LineValue $LogLine
    }
    else {
       Continue
    }
}

#----------------------------------------------[ Execution ]------------------------------------------------


Foreach ($Manager in $Managers) {
    if (-not $logonly) {
    $Directreports = Get-Directreport $manager -norecurse  | Select-Object -expand samAccountName
    $script:AddUserCount = ($DirectReports | Measure-Object).count++
    $time = (Get-Date).ToString('T')
        New-bhReportToGroup
        Get-bhDReports
        Set-bhRTGmembers
        Log-Write -LogPath $sLogFile -LineValue "Direct reports are: $Directreports"
        Log-Write -LogPath $sLogFile -LineValue "========================[$Time ]==============================="
        
 } else {
        $script:LOAddUserCount = ($DirectReports | Measure-Object).count++
        New-bhReportToGroup_logonly
        Get-bhDReports
        Set-bhRTGmembers_logonly
        Log-Write -LogPath $slogonlyFile -LineValue "========================[ logonly ]==============================="  
    }
  }
Foreach ($Report in $ReportsTo) {
    If (-not $logonly){
    Remove-bhOOSGroups
} else {
    #ForEach ($Report in $ReportsTo) {
    Remove-bhOOSGroups_logonly
        }
   }
#}

if (-not $logonly) {
    Log-Write -Logpath $sLogPath -Linevalue "$AddUserCount New users added to groups"
    Log-Write -LogPath $sLogPath -Linevalue "$AddGroupCount New groups added"
    Log-Write -LogPath $sLogPath -Linevalue "$GroupsRemoved groups removed"
    Log-Write -LogPath $sLogPath -Linevalue "====[END]====="
} else {
    Log-Write -Logpath $slogonlyPath -Linevalue "$LOAdduserCount Users who would be added"
    Log-Write -Logpath $slogonlyPath -Linevalue "$LOGroupCount Groups that would be added"
    Log-Write -LogPath $slogonlyPath -Linevalue "$LOGroupsRemoved Groups that would be removed"
    Log-Write -LogPath $slogonlyPath -Linevalue "====[END]====="
}

我指的是执行部分中以 $script:AddUserCount = ($DirectReports | Measure-Object).count++ 开头和它的替代 $script:LOAddUserCount = ($DirectReports | Measure-Object).count++ 的行。现在,如果您正常运行或使用 -logonly 运行,返回的值是最后一次循环迭代的值......不是所有迭代的总和。

关于如何完成这样的事情有什么想法吗?

解决方法

如果您想添加到现有值,请使用 += 而不是 =

$script:AddUserCount += @($DirectReports |Measure-Object).Count

... 或者,如果您更喜欢长格式:

$script:AddUserCount = $script:AddUserCount + @($DirectReports |Measure-Object).Count