Skipping lines

Is there any GENERAL reason why my powershell script would skip executing several lines of code? And its the same “block” of code every time I run it.

There is no chance at all to reasonably answer this question without seeing the actual code.

Need to see your script. There could be multiple reasons: exceptions, User/system context execution and so on.

Good Morning All,

Thank you for your help. Please my code below. Forgive any sloppiness of my code. I am self-taught and do not have any formal training in Powershell scripting. Always learning.

What the code is doing?

I am connecting to ServiceDesk/Fresh Service API to pull information from a ticket and then finding the User in Active Directory to gather information and shutdown their account. The code starting from “Import-Module ActiveDirectory” to “#Retrieves the OUs in CA4K” is the piece the will NOT execute.
[Editor’s Note: with the code properly formatted, the problem section is shown as marked lines rather than red colored text. Specifically, lines 297-468]

Any ideas by simply looking at my code? No errors occur up until this point.

P.s. I replaced some variable information to protect data.

CODE BELOW:

#This is where we define the parameters.
#It prompts Service Request ID, ComputerName via IP
    Param (
        [Parameter(Mandatory=$true)]
            [string]$SRID,
        [Parameter(Mandatory=$true)]
            [string]$ComputerIP,
        [Parameter(Mandatory=$false)]
            [string]$managerpermissions,
        [Parameter(Mandatory=$false)]
            [string]$AdditionalUserpermissions,
        [Parameter(Mandatory=$false)]
            [string]$email,
        [Parameter(Mandatory=$false)]
            [string]$ManagerEmailAddress,
        [Parameter(Mandatory=$false)]
            [string]$AdditionalUserEmailAddress
    )
    $credential = Get-Credential
    $CredentialforAPI = ($credential | Select-Object username).username
#----------------------------------------------------------------------------------------------------
#Retrieves SAMAccountName of Termed User from Offboarding ticket
    $Variable = "EmailAddress",'AnApikey'
    $Variable = "EmailAddress",'AnApikey'
    $Variable = "EmailAddress",'AnApikey'
    $Variable = "EmailAddress",'AnApikey'
    $Variable = "EmailAddress",'AnApikey'
    $Variable = "EmailAddress",'AnApikey'
    $Terminators = @($Variable, $Variable, $Variable, $Variable, $Variable, $Variable)
    Foreach($Terminator in $Terminators){
        if($Terminator -contains $CredentialforAPI){
            $Key = $Terminator.split(',')[1]

        }
    }

    $apikey = $Key
    $thekey = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$apikey"))
    $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
    $headers.Add('authorization', ("Basic {0}" -f $thekey))
    $headers.Add('content-type', 'application/json')
    $uri = "https://servicedesk.intlfcstone.com/helpdesk/tickets/$SRID.json"
    $response = (Invoke-RestMethod -Uri $uri -Headers $headers -Method Get -ContentType "application/json").helpdesk_ticket.subject -replace ".*- "
    #Try to Match Subject line with 'Name' field in AD Manager Plus to get the SAMAccountName of the User (Ex. FirstName LastName)
    $Username = (Get-ADUser -filter { Name -eq $response } | Select-object Samaccountname).samaccountname
        if ($Username -ne $response){
            #Try to Match Subject line with 'DisplayName' field in AD Manager Plus to get the SAMAccountName of the User (Ex. FirstName LastName)
            $Username = (Get-ADUser -filter { DisplayName -eq $response } | Select-Object Samaccountname).samaccountname
            $ErrorActionPreference= 'silentlycontinue'
        }else{
            #Try to match Subject line with 'SAMAccountName' field in AD Manager Plus to get the SAMAccountName of the User (Ex. FirstName.LastName)
            $Username = (Get-ADUser -filter { Samaccountname -eq $response } | Select-Object Samaccountname).samaccountname
            $ErrorActionPreference= 'silentlycontinue'
        }

        if($null -eq $Username){
            #Type in SAMAccountName. If you mistype you will have to start the script over by pressing F5.
            $Username = Read-Host "Could not find User's AD Account. Please type in SAMAccountName"
        }
        Write-Host
        Write-Host "TERMED USER:" -ForegroundColor Yellow
        Write-Host "You are terming $Username" -ForegroundColor Green
#----------------------------------------------------------------------------------------------------
#START TRANSCRIPT
$Transcript = Start-Transcript -Path  "\\---------\mis\Systems Access\Termination-Transcripts\$Username-Termination.txt" #-NoClobber -IncludeInvocationHeader
#----------------------------------------------------------------------------------------------------
#REGION VARIABLES
$CSVPath = "\\--------\mis\Systems Access\Excel Sheets -Terminations\$Username`_GU_$SRID.csv"
$CSVPathAddminAccounts = "\\---------\mis\Systems Access\Excel Sheets -Terminations\$Username`_AddAcct_$SRID.csv"
$TerminatedUserTargetOU = 'OU=TerminatedEmployeesContractors,OU=Corporate,DC=FCStone,DC=com'
$LegalHoldGroup = "GG-AUD_LG_LegalHold"
#$3rdPartyAPPADGroup = "GG-AUD_SA"
$Date = Get-Date
$EXManager = (get-aduser (get-aduser $Username -Properties manager).manager).samaccountname
$managerEmailAddress = (Get-Aduser $EXManager -properties EmailAddress).EmailAddress
#END REGION------------------------------------------------------------------------------------------
#Lookup Email address for AD User
if([string]::IsNullOrEmpty($email)){
    write-host
    write-host "Looking up the email address for $Username..." -ForegroundColor Yellow
    $adUser = get-aduser $Username -Properties mail
    $email = $adUser.mail
    Write-Host "Found $email as the Email Address for $Username"
    }
Write-Host
Write-Host "MANAGER" -ForegroundColor Yellow
write-host $EXManager -ForegroundColor Green
write-host
#----------------------------------------------------------------------------------------------------
#This is where the computer the User currently owns will be rebooted
Write-host "COMPUTER REBOOT/SHUTDOWN" -ForegroundColor Yellow
Shutdown -r -m \\$ComputerIP -t 0 -f
Write-Host "Rebooting/Shutting down User's computer" -ForegroundColor Green
#----------------------------------------------------------------------------------------------------
#PASSWORD RESET
function Get-RandomCharacters($length, $characters) {
    $random = 1..$length | ForEach-Object { Get-Random -Maximum $characters.length }
    $private:ofs=""
    return [String]$characters[$random]
}
function Scramble-String([string]$inputString){
    $characterArray = $inputString.ToCharArray()
    $scrambledStringArray = $characterArray | Get-Random -Count $characterArray.Length
    $outputString = -join $scrambledStringArray
    return $outputString
}
$NewPassword = Get-RandomCharacters -length 6 -characters 'abcdefghiklmnoprstuvwxyz'
$NewPassword += Get-RandomCharacters -length 4 -characters 'ABCDEFGHKLMNOPRSTUVWXYZ'
$NewPassword += Get-RandomCharacters -length 3 -characters '1234567890'
$NewPassword += Get-RandomCharacters -length 2 -characters '!$%&/()?@#*+'
$NewPassword = Scramble-String $NewPassword
Set-ADAccountPassword -Identity $Username -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "$NewPassword" -Force)
Write-Host
Write-Host "PASSWORD RESET" -ForegroundColor Yellow
Write-host 'Password has been reset' -ForegroundColor Green
#----------------------------------------------------------------------------------------------------
#EXCHANGE
#Connect to MS Online PowerShell
Try {
    Connect-MsolService -Credential $credential
}
Catch {
    write-host
    write-host 'Unable to connect to MS Online PowerShell - Please ensure you have the MS Online PowerShell Module installed for your ADMIN ACCOUNT. Please reach out to DG-EToolsOps if you have any questions or concerns.' -ForegroundColor Red -BackgroundColor Black
    throw
}
#Connect to Exchange Online PowerShell
Try {
    $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $credential -Authentication Basic -AllowRedirection
    Import-PSSession $Session -DisableNameChecking -AllowClobber
}
Catch {
    write-host
    write-host 'Unable to Connect Exchange Online PowerShell. Please reach out to DG-EToolsOps if you have any questions or concerns.' -ForegroundColor Red
    throw
}
#Connect to Security and Compliance PowerShell
Try {
    $ScSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.compliance.protection.outlook.com/powershell-liveid/ -Credential $credential -Authentication Basic -AllowRedirection
    Import-PSSession $ScSession -DisableNameChecking -AllowClobber
}
Catch {
    write-host
    write-host 'Unable to Connect Security and Compliance PowerShell. Please reach out to DG-EToolsOps if you have any questions or concerns.' -ForegroundColor Red
    throw
}
#Prompt - Does Manager need access to mailbox?
if([string]::IsNullOrEmpty($Managerpermissions)){
    Write-Host
    Write-Host "MANAGER PERMISSIONS" -ForegroundColor Yellow
    $Managerpermissions = Read-Host "Does Manager need access to the mailbox? (y/n)"
}
#Collect Managers (and others) Email Address
if ($Managerpermissions -eq "y" -or $Managerpermissions -eq "Y"){

    Write-Host "Working on adding FullAccess permissions for $ManagerEmailAddress to $email..."
    Add-MailboxPermission -Identity $email -User $ManagerEmailAddress -AccessRights FullAccess -InheritanceType All
#Converting Mailbox to Shared
    write-host
    Write-host "Working on converting $email to a shared mailbox..." -ForegroundColor Yellow
    write-host
    try {
        set-mailbox "$email" -type shared
    }
    catch {
        Write-host
        Write-Host "WARNING: We were unable to convert $email to a shared mailbox. Please log into the Exchange Admin Center at https://outlook.office365.com/ecp and convert $email to a shared mailbox manually." -ForegroundColor Red
        write-host
    }
#Verify converting Mailbox to Shared
$convert = get-mailbox "$email"
    if ($convert.RecipientTypeDetails -eq "SharedMailbox"){
        write-host
        write-host $email is now: $convert.RecipientTypeDetails -ForegroundColor Green
        write-host
    }
    else {
        write-host
        write-host WARNING - $email is a $convert.RecipientTypeDetails -ForegroundColor Red
        write-host
    }
}
elseif ($Managerpermissions -eq "n" -or $Managerpermissions -eq "N"){
    $6monthHoldGroup = @()
    $6monthHoldGroup += Get-DistributionGroupMember -Identity "DG-Compliance EMEAA" | Select-Object PrimarySmtpAddress
    $6monthHoldGroup += Get-DistributionGroupMember -Identity "DG-Compliance Global Relay" | Select-Object PrimarySmtpAddress
    $6monthHoldGroup += Get-DistributionGroupMember -Identity "DG-Compliance IFFBD" | Select-Object PrimarySmtpAddress
    $6monthHoldGroup += Get-DistributionGroupMember -Identity "DG-Compliance IFS" | Select-Object PrimarySmtpAddress
    $6monthHoldGroup += Get-DistributionGroupMember -Identity "DG-Compliance Recording" | Select-Object PrimarySmtpAddress
    $6monthHoldGroup += Get-DistributionGroupMember -Identity "DG-Compliance Reporting" | Select-Object PrimarySmtpAddress
    $6monthHoldGroup += Get-DistributionGroupMember -Identity "DG-Compliance SA" | Select-Object PrimarySmtpAddress
    $6monthHoldGroup += Get-DistributionGroupMember -Identity "DG-Compliance Sanctions Report" | Select-Object PrimarySmtpAddress
    $6monthHoldGroup += Get-DistributionGroupMember -Identity "DG-Compliance Term Notification" | Select-Object PrimarySmtpAddress
    $6monthHoldGroup += Get-DistributionGroupMember -Identity "DG-ComplianceHK" | Select-Object PrimarySmtpAddress
    $6monthHoldGroup += Get-DistributionGroupMember -Identity "DG-Legal" | Select-Object PrimarySmtpAddress
    $6monthHoldGroup += Get-DistributionGroupMember -Identity "DG-Legal Chicago" | Select-Object PrimarySmtpAddress
    $6monthHoldGroup += Get-DistributionGroupMember -Identity "DG-Legal Compliance Brazil" | Select-Object PrimarySmtpAddress
    $6monthHoldGroup = $6monthHoldGroup.PrimarySmtpAddress
    if($6monthHoldGroup -contains $email){
        Set-RetentionCompliancePolicy -Identity "6 Month Terminated User Email Retention" -AddExchangeLocation $email
    }
    else{
        Set-RetentionCompliancePolicy -Identity "30 day terminated user email retention" -AddExchangeLocation $email
    }
}
Write-Host
Write-Host "ADDITIONAL USER PERMISSIONS" -ForegroundColor Yellow
#ADDITIONAL USER
#Prompt - Does Manager need access to mailbox?
if([string]::IsNullOrEmpty($AdditionalUserpermissions)){
    $AdditionalUserpermissions = Read-Host "Does an Additional User need access to the mailbox? (y/n)"
}
#Collect Additional User Email Address
if($AdditionalUserpermissions -eq "y" -or $AdditionalUserpermissions -eq "Y"){
    write-host
    $AdditionalUserEmail = Read-Host "What is the Additional User's Email Address?"
}
#Lookup Email address for AD User
if([string]::IsNullOrEmpty($email)){
    write-host
    write-host "Looking up the email address for $Username..." -ForegroundColor Yellow
    $adUser = get-aduser $Username -Properties mail
    $email = $adUSer.mail
    Write-Host "Found $email as the Email Address for $Username"
    }
#Cancel Calendar Events
Write-Host
Write-Host "CALENDAR EVENTS" -ForegroundColor Yellow
Write-host "Working on canceling $email's calendar events..." -ForegroundColor Cyan
write-host
try {
    Remove-CalendarEvents -Identity $email -CancelOrganizedMeetings -Confirm:$False -QueryWindowInDays 1825
    Write-host "Removed calendar events for $email" -ForegroundColor Green
}
Catch {
    Write-host
    Write-Host "WARNING: We were unable to cancel the calendar events for $email." -ForegroundColor Red
    write-host
}
#Apply Additional User Permissions
Switch ($AdditionalUserpermissions)
 {
   Y {
        write-host
        Write-Host "Working on adding FullAccess permissions for $AdditionalUserEmail to $email..."
        Add-MailboxPermission -Identity $email -User $AdditionalUserEmail -AccessRights FullAccess -InheritanceType All
        Start-Sleep 10
        Get-MailboxPermission $email| Where-Object{$_.User -like "$AdditionalUserEmail"} | Select-Object accessrights,user,identity | Format-List
    }
   N {}
   Default {}
 }
#----------------------------------------------------------------------------------------------------
Start-Sleep -Seconds 10
#----------------------------------------------------------------------------------------------------
#Adds Out of Office Messages
Write-Host
Write-Host "OUT OF OFFICE MESSAGE" -ForegroundColor Yellow
$EXManager -replace "."," "
$CustomOOOQuestion = Read-host "Does the User's Service Request Ticket have a custom Out Of Office message, (Y/N)?"
if($CustomOOOQuestion -eq "Y"){

    $CustomOOOMessage = Read-Host "What is the Custom OOO Message?"
    Set-MailboxAutoReplyConfiguration -Identity $email -AutoReplyState Enabled -InternalMessage "$CustomOOOMessage" -ExternalMessage "$CustomOOOMessage"
    Write-host "Custom Out Of Office Message has been added." -ForegroundColor Green
}elseif($CustomOOOQuestion -eq "N"){
    Set-MailboxAutoReplyConfiguration -Identity $email -AutoReplyState Enabled -InternalMessage "Hello, I am no longer with StoneX. If you have questions please contact:
    $EXManager at $ManagerEmailAddress" -ExternalMessage "Hello, I am no longer with StoneX. If you have questions please contact:
    $EXManager at $ManagerEmailAddress"
    Write-host "Default Out of Office Message has been added." -ForegroundColor Green
}
#----------------------------------------------------------------------------------------------------
#Removing Licenses
Write-Host
Write-Host "REMOVING LICENSES" -ForegroundColor Yellow
$licenseGroups = Get-ADPrincipalGroupMembership $Username | Where-Object{$_.name -like "*sg-lic*"}
If ($null -ne $licenseGroups){
    write-host
    Write-Host "$Username has group based licensing. The Office 365 License will be removed within 1 hour."
}
Else {
    try {
        $userLicenses += @((get-MsolUser -UserPrincipalName $email).licenses.AccountSkuId)
        foreach ($sku in $userLicenses){
            Set-MsolUserLicense -UserPrincipalName "$email" -RemoveLicenses $sku -ErrorAction Ignore
            Start-Sleep 5
        }
    }
    catch {
        Write-host
        Write-Host "WARNING: We were unable to remove the license automatically." -ForegroundColor Red
        write-host
    }
#----------------------------------------------------------------------------------------------------
#Start-Sleep -Seconds 5
#----------------------------------------------------------------------------------------------------
Import-Module activedirectory
#Admin
Write-Host
Write-Host "ELEVATED ACCOUNTS" -ForegroundColor Yellow
$ElevatedUser = Get-ADUser -Identity $Username -Properties *
$GivenName = $ElevatedUser.GivenName
$Surname = $ElevatedUser.Surname.Substring(0,1)
$GSAdmin = $GivenName + $Surname + "-Adm"
$GSSupport = $GivenName + $Surname + ".Support"
$GSTest = $GivenName + $Surname + ".Test"
$GAdmin = $GivenName + "-Adm"
$GSupport = $GivenName + ".Support"
$GTest = $GivenName + ".Test"
    try {
        Write-host "Admin Account(s)" -ForegroundColor Yellow
        $GSAdmin00 = Get-ADUser -Identity $GSAdmin -Properties Name
        $GSAdmin01 = Get-ADUser -Identity $GSAdmin -Properties SamaccountName
        $GSAdmin02 = Get-ADUser -Identity $GSAdmin -Properties DisplayName
        $GSAdmin01 | Export-Csv -Path $CSVPathAddminAccounts -NoTypeInformation
        Write-Host "$GSAdmin01 has been found." -ForegroundColor Green
    }
    catch {
    
        Write-Host "$GSAdmin01 Account does not exist." -foregroundcolor Red
        
    }
    try {
        
        $GAdmin00 = Get-ADUser -Identity $GAdmin -Properties Name
        $GAdmin01 = Get-ADUser -Identity $GAdmin -Properties SAMAccountName
        $GAdmin02 = Get-ADUser -Identity $GAdmin -Properties DisplayName
        $GAdmin01 | Export-Csv -Path $CSVPathAddminAccounts -NoTypeInformation
        Write-Host "$GAdmin01 has been found." -ForegroundColor Green
    }
    catch { 
        
        Write-Host "$GAdmin01 Account does not exist." -foregroundcolor Red
        
    }
    #Support
    try { 
        Write-host
        Write-host "Support Account(s)" -ForegroundColor Yellow
        $GSSupport00 = Get-ADUser -Identity $GSSupport -Properties Name
        $GSSupport01 = Get-ADUser -Identity $GSSupport -Properties SAMAccountName
        $GSSupport02 = Get-ADUser -Identity $GSSupport -Properties DisplayName
        $GSSupport01 | Export-Csv -Path $CSVPathAddminAccounts -NoTypeInformation
        Write-Host "$GSSupport01 has been found." -ForegroundColor Green
    }
    catch { 
        
        Write-Host
        Write-Host "$GSSupport01 Account does not exist." -foregroundcolor Red
        
    }
    try { 
    
        $GSupport00 = Get-ADUser -Identity $GSupport -Properties Name
        $GSupport01 = Get-ADUser -Identity $GSupport -Properties SAMAccountName
        $GSupport02 = Get-ADUser -Identity $GSupport -Properties DisplayName
        $GSupport01 | Export-Csv -Path $CSVPathAddminAccounts -NoTypeInformation
        Write-Host "$GSupport01 has been found." -ForegroundColor Green
    }
    catch { 
        Write-Host
        Write-Host "$GSupport01 Account does not exist." -foregroundcolor Red
        
    }
    #Test
    try { 
        Write-host
        Write-host "Test Account(s)" -ForegroundColor Yellow
        $GSTest00 = Get-ADUser -Identity $GSTest -Properties Name
        $GSTest01 = Get-ADUser -Identity $GSTest -Properties SAMAccountName
        $GSTest02 = Get-ADUser -Identity $GSTest -Properties DisplayName
        $GSTest01 | Export-Csv -Path $CSVPathAddminAccounts -NoTypeInformation
        Write-Host "$GSTest01 has been found." -ForegroundColor Green
    }
    catch { 
        
        Write-Host
        Write-Host "$GSTest01 Account does not exist." -foregroundcolor Red   
        
    }
    try { 
        $GTest00 = Get-ADUser -Identity $GTest -Properties Name
        $GTest01 = Get-ADUser -Identity $GTest -Properties SAMAccountName
        $GTest02 = Get-ADUser -Identity $GTest -Properties DisplayName
        $GTest01 | Export-Csv -Path $CSVPathAddminAccounts -NoTypeInformation
        Write-Host "$GTest01 has been found." -ForegroundColor Green
    }
    catch {
    
        Write-Host
        Write-Host "$GTest01 Account does not exist." -foregroundcolor Red
        
    }
#----------------------------------------------------------------------------------------------------
#AUDIT GROUP CHECKLIST
$AuditGroups = (Get-ADUser -identity $Username -properties * | Select-object MemberOf).MemberOf | Sort-Object
$AGSelection = $AuditGroups | Select-String -pattern "GG-AUD_SA"
$AGroups = $AGSelection -replace "CN=","" -replace ",OU.*",""
Write-Host
Write-Host "AUDIT APPLICATION GROUPS:"-foregroundcolor Yellow
Write-Host "Press [Y] when finished." -foregroundcolor Green
ForEach($AG in $AGroups){
    
    $confirmation = Read-Host "$AG"
        while ($confirmation -ne 'y') {
            $confirmation = Read-Host "$AG"
        }
   
}
#----------------------------------------------------------------------------------------------------
#Direct Reports
Write-Host
Write-Host "RETRIEVING DIRECT REPORTS" -ForegroundColor Yellow
Try {
    $DirectReportUser = (Get-ADUser -identity $Username -properties * | Select-Object DirectReports).DirectReports | Sort-Object
    $DRUser = $DirectReportUser -replace "CN=","" -replace ",OU=.*",""
    $DRUser
    Set-ADUser -Identity $Username -Manager $EXManager
    Write-Host "New ownership of Direct Reports is $EXManager"-ForegroundColor Green
}catch{
    Write-Host "$Username does not have any direct reports." -ForegroundColor Red
}
#----------------------------------------------------------------------------------------------------
#Group Ownership
Write-Host
Write-Host "CHANGING OWNERSHIP OF GROUPS" -ForegroundColor Yellow
Try {
    $GroupOwnerUser = (Get-ADUser -identity $Username -properties * | Select-Object ManagedObjects).ManagedObjects | Sort-Object
    $GOUser = $GroupOwnerUser -replace "CN=","" -replace ",OU=.*",""
    $GOUser
    Set-ADGroup -Identity $GOUser -ManagedBy $EXManager
    Write-Host "New ownership of groups is now $EXManager"-ForegroundColor Green
}catch{
    Write-Host "$Username does not own any groups." -ForegroundColor Red
}
#----------------------------------------------------------------------------------------------------
#Retrieves User's Groups
Write-Host
Write-Host "EXPORTING USER'S GROUPS" -ForegroundColor Yellow
Try {
    $user = get-aduser -Identity $Username -Properties memberof
    $groups = $user.memberof | Sort-Object
    $csv = foreach($Group in $Groups){
        Get-adgroup $Group | Select-Object Name
        
    }
    $csv | Export-Csv $CSVPath -NoTypeInformation
    Write-Host "$Username's groups have been export to CSV." -ForegroundColor Green
}catch{
    Write-Host "$Username did not export." -ForegroundColor Red
}
#----------------------------------------------------------------------------------------------------
#Verifying license removal
Write-Host
Write-Host "LICENSE REMOVAL" -ForegroundColor Yellow
$licenses = (get-MsolUser -UserPrincipalName $email).licenses.AccountSkuId
    if ($null -eq $licenses){
    
        Write-host "All Licenses have been removed for $email" -ForegroundColor Green
        write-host
    }
    else {
        
        Write-Host "$email has $licenses. Please log into the Admin Center at portal.office.com and remove the licenses for $email manually." -ForegroundColor Red
        write-host
    }
}
#----------------------------------------------------------------------------------------------------
#Retrieves the OUs in CA4K
Write-Host
Write-Host "CA4K (CHECKING OUs)" -ForegroundColor Yellow
$OU = @(
    "OU=Alpharetta,OU=US,OU=Corporate,DC=FCStone,DC=com",
    "OU=Birmingham,OU=US,OU=Corporate,DC=FCStone,DC=com",
    "OU=BocaRaton,OU=US,OU=Corporate,DC=FCStone,DC=com",
    "OU=BowlingGreen,OU=US,OU=Corporate,DC=FCStone,DC=com",
    "OU=Chicago,OU=US,OU=Corporate,DC=FCStone,DC=com",
    "OU=Dallas,OU=US,OU=Corporate,DC=FCStone,DC=com",
    "OU=KansasCity,OU=US,OU=Corporate,DC=FCStone,DC=com",
    "OU=Miami,OU=US,OU=Corporate,DC=FCStone,DC=com",
    "OU=NewYork,OU=US,OU=Corporate,DC=FCStone,DC=com",
    "OU=Omaha,OU=US,OU=Corporate,DC=FCStone,DC=com",
    "OU=ParkCity,OU=US,OU=Corporate,DC=FCStone,DC=com",
    "OU=WinterPark,OU=US,OU=Corporate,DC=FCStone,DC=com")
foreach($OU1 in $OU){
    $OU2 = (Get-ADUser -Filter * -SearchBase $OU1 | Select-Object DistinguishedName).DistinguishedName
    $UsernameInOU = (Get-ADUser -Identity $Username -Properties * | Select-Object DistinguishedName).DistinguishedName
        if($UsernameInOU -in $OU2){

            Write-Host "YES, Location exists in CA4K. Please check in CA4K Badge System for $Username" -ForegroundColor Green
        }else{

            $OU1
            Write-host "No, Location does NOT exists in CA4K. $Username May not be in CA4K Badge System" -ForegroundColor Red
        }
}
#----------------------------------------------------------------------------------------------------

Wow quite a large, involved piece of code for self-taught beginner. The main thing I see that would prevent the code block you identified from executing is you start an else block on line 281 and it doesn’t close until line 467, so if the condition on 277 evaluates to $true then that block of code will not execute. With that in mind here are some considerations.

  1. Looking at the code indentation, it seems you may have intended to close that else block out after line 293.
  2. With a given data set can you test a condition that will ensure line 277 will evaluate to false so you can troubleshoot the else block?
 

As you are finding, this code is a bit unmanageable and difficult to troubleshoot. My suggestion, is to work on making your code much more modular, basically creating functions. A few examples:

function New-IFSCPassword {
    [CmdletBinding()]
    param()
    begin {
        function Get-RandomCharacters($length, $characters) {
            $random = 1..$length | ForEach-Object { Get-Random -Maximum $characters.length }
            $private:ofs=""
            return [String]$characters[$random]
        }
        function Scramble-String ([string]$inputString) {
            $characterArray = $inputString.ToCharArray()
            $scrambledStringArray = $characterArray | Get-Random -Count $characterArray.Length
            $outputString = -join $scrambledStringArray
            return $outputString
        }
    }
    process {
        $NewPassword = Get-RandomCharacters -length 6 -characters 'abcdefghiklmnoprstuvwxyz'
        $NewPassword += Get-RandomCharacters -length 4 -characters 'ABCDEFGHKLMNOPRSTUVWXYZ'
        $NewPassword += Get-RandomCharacters -length 3 -characters '1234567890'
        $NewPassword += Get-RandomCharacters -length 2 -characters '!$%&/()?@#*+'
        $results = Scramble-String $NewPassword
    }
    end {
        $results
    }
}
function Get-FreshServiceRequest {
    [CmdletBinding()]
    param(
        [int]$Id,
        [PSCredential]$Credential
    )
    begin {}
    process {    
        $CredentialforAPI = ($credential | Select-Object username).username
        #----------------------------------------------------------------------------------------------------
        #Retrieves SAMAccountName of Termed User from Offboarding ticket
        $Variable = "EmailAddress",'AnApikey'
        $Variable = "EmailAddress",'AnApikey'
        $Variable = "EmailAddress",'AnApikey'
        $Variable = "EmailAddress",'AnApikey'
        $Variable = "EmailAddress",'AnApikey'
        $Variable = "EmailAddress",'AnApikey'
        $Terminators = @($Variable, $Variable, $Variable, $Variable, $Variable, $Variable)
        Foreach($Terminator in $Terminators){
            if($Terminator -contains $CredentialforAPI){
                $Key = $Terminator.split(',')[1]
            }
        }
    
        $apikey = $Key
        $thekey = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$apikey"))
        $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
        $headers.Add('authorization', ("Basic {0}" -f $thekey))
        $headers.Add('content-type', 'application/json')
        $uri = "https://servicedesk.intlfcstone.com/helpdesk/tickets/$Id.json"
        $response = (Invoke-RestMethod -Uri $uri -Headers $headers -Method Get -ContentType "application/json").helpdesk_ticket.subject -replace ".*- " 
    }
    end {
        $response
    }
}

Breaking the code into functional pieces makes the code much easier to manage. Other examples are shared mailbox, you might do a function ConvertTo-SharedMbx or Set-ExchanceOutOfOffice for setting the out of office. Other things I see is you have try\catch statements, but the -ErrorAction is not set to Stop, so it will not catch the exceptions. Another item is you are doing a ton of queries to AD. I’m not sure what the goal is to find 3 things and then export a single item to a CSV either, but this:

$GSupport00 = Get-ADUser -Identity $GSupport -Properties Name
$GSupport01 = Get-ADUser -Identity $GSupport -Properties SAMAccountName
$GSupport02 = Get-ADUser -Identity $GSupport -Properties DisplayName

should be more like:

$GSupport = Get-ADUser -Identity $GSupport -Properties Name, SAMAccountName, DisplayName

Those properties are always returned, i.e. default properties, so you do not need to specify the properties. You specify the properties when it’s a non-default property like Manager or Department that is not returned. In the beginning you are doing 3 queries to find the user with 3 different filters, which can be done in a single query as well. It is going to be difficult for folks to help as this is a really long script and we cannot step thru it easily. I’d start with trying to convert to functions and your script should be outlined like this:

–functions
–variables
–script (call functions with variables)

Mike R,

You have HELPED ME OUT TREMENDOUSLY!!! That was the issue. My ‘else’ statement was NOT closed. I feel like such a fool. Thank you so much. I will take Rob Simmers’s advice and get this code cleaned up, so I don’t miss little things like this.

Thank you to the both of you for all of your help. I’m sure I’ll be back. lol

 

Thank you Rob. I will definitely make sure to get my code cleaned up.

 

Thank you for your help.

[quote quote=291541]Thank you Rob. I will definitely make sure to get my code cleaned up.
[/quote]

Using a proper IDE like VSCode could help you as well. That would help debugging your code.

Olaf,

You know the funny thing is I build my scripts in VSCODE (I love it.) I ran my debugger and went line by line and it still didn’t catch it. Which is one of the reasons I was having such a hard time finding what was wrong. Very strange. I’m still very grateful for your advice though.

One other thing that might help especially when you have lengthy code is to close out script blocks on a separate line (when feasible) and comment what you are closing. i.e.

foreach ($item in $collection){
    switch ($item) {
        'value1' {}
        Default  {}
    } #switch (item)
} #foreach (item in collection)

 

Mike R.

Can do my friend.

 

Thank you,