LogOnly 函数有问题,计数不正确

Problem with LogOnly functions, not counting properly

好的..我在下面有这个脚本,它 运行 -LogOnly 参数应该给出总计数,如:

DEBUG: ========================[ LogOnly ]===============================
DEBUG: aaqa.www user has fell out of scope, Report group would be removed.
DEBUG: 0 Users who would be added
DEBUG: 0 Groups that would be added
DEBUG: 1 Groups that would be removed
DEBUG: ====[END]=====

因此,如果您看到 0 Users who would be added 是不正确的。我从 AD 的安全组中删除了 2 个用户(在范围内),但他们没有被计算在内。我在做这个的时候在几个不同的地方都有 $script:AddUserCount += ($DirectReports | Measure-Object).count 所以我很困惑把它放在哪里才能完成这项工作。它也没有正确地计算在没有 LogOnly 参数的情况下调用脚本时添加的用户,在这种情况下,它计算与 Get-DirectReports 函数匹配的所有用户。如果您 运行 立即第二次 w/o LogOnly,它仍将 return 完整的 1600 个用户计数。我觉得修复一个会修复两个。 这是脚本:

#---------------------------------------------------------[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'"
    $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."
        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 {
    Remove-bhOOSGroups_logonly
        }
   }
#}

if (-not $LogOnly) {
    Log-Write -Logpath $sLogPath -Linevalue "$AddUserCount Total users matched"
    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]====="
}

"$AddUserCount Total users matched" 不是正在输出的变量。是这个:"$LOAdduserCount Users who would be added"

此外,$script:LOAddUserCount += ($DirectReports | Measure-Object).count 不应出现在 $script: 上下文中。应该是 $LOAddUserCount += $DirectReports.Count,注意我也简化了计数。