Disable AD user powershell script error

Airlenn 1 Reputation point
2021-07-30T00:49:53.2+00:00

Hi,

FYI - I have only started my powershell/scripting journey so please forgive my lack of knowledge.

I have inherited a PS script to disable inactive users in AD after 30 days of inactivity.
The script also outputs to a .txt file, a .csv file, and writes into the "notes" field in the telephone tab of the AD user.
The script has been working. But we have now noticed that when the a user has been disabled before and there is an entry in the notes field. The output won't overwrite or add to the notes field when the user is diabled again.

So the correct output is
Disabled due to inactivity - 20/07/2021

The subsequent error output is
CN=Firstname Lastname,OU=Users,DC=mydomain,DC=com

We also get the error below when running the PS

Method invocation failed because [Microsoft.ActiveDirectory.Management.ADUser]
does not contain a method named 'op_Addition'.
At E:\inactiveusers\inactiveusers.ps1:58 char:21

  • $Info += " $UpdateInformation - $Date"
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  • CategoryInfo : InvalidOperation: (op_Addition:String) [], Runti
    meException
  • FullyQualifiedErrorId : MethodNotFound

Here is the full script
Any help is appreciated.

<#   
    TO RUN:  
    .\Disable-InactiveUsers.ps1 -Remediate    
#>   

[CmdletBinding()]   
param (             
        [Parameter( Mandatory=$false)]   
        [int]$TimeFrame = 30,   

        [Parameter( Mandatory=$false)]   
        [string]$UpdateInformation = "Disabled due to inactivity",   

        [Parameter( Mandatory=$false)]   
        [switch]$Remediate,   

        [Parameter( Mandatory=$false)]   
        [string]$LogName = "UserLogNew.txt",   

        [Parameter( Mandatory=$false)]   
        [string]$ExclusionsPath = "\\mydomain.com\files\IT\Scripts\InactiveUsers\exclusions.txt",   

        [Parameter( Mandatory=$false)]   
        [string]$TriggeredPath = "\\mydomain.com\files\IT\Scripts\InactiveUsers\DisabledLogNew.csv"   
    )   
$Date = Get-Date -Format "dd/MM/yyyy"   
$LogDate = Get-Date -Format "yyyy MM dd - HH:mm:ss tt"   
$myDir = Split-Path -Parent $MyInvocation.MyCommand.Path   
$LogPath = "\\mydomain.com\files\IT\Scripts\InactiveUsers\UsersLogNew.txt"  
$Report = New-Object PSObject   
$TriggeredUsers = @()   
$Exclusions = Get-Content $ExclusionsPath   

Import-Module ActiveDirectory   

$users = Get-ADUser -Properties name, lastlogondate, SamAccountName, Info -filter {(enabled -eq $true -and SamAccountName -notlike "*service*" -and SamAccountName -notlike "*svc*" -and SamAccountName -notlike "*cnw*")} -SearchBase 'ou=users,dc=mydomain,dc=com'  

Function Write-LogFile {   
    [CmdletBinding()]   
    param(   
        [Parameter( Position=0,Mandatory=$true)]   
        [string]$LogData   
        )   
    "$Date - $LogData" | Out-file -FilePath $LogPath -Append  
}   

foreach ($User in $Users) {   
    $UserName = $User.DistinguishedName  
    if ($Exclusions -notcontains $User.SamAccountName) {   
        if ($User.LastLogonDate -lt (Get-Date).AddDays(-$TimeFrame) -AND $User.LastLogonDate -ne $null) {   
            if ($Remediate) {   
                if ($UpdateInformation -ne $null) {   
                    $Info = Get-ADUser $UserName -Properties info | Where-Object {$_.info}   
                    $Info += " $UpdateInformation - $Date"   
                    try {   
                        Set-ADUser -Identity $UserName -Replace @{info="$Info"} -ErrorAction Stop   
                        Write-LogFile -LogData "Successfully set Info field for $($User.Name). New Info: $UpdateInformation - $Date"   
                        }   
                    catch {   
                        Write-LogFile -LogData "Error - Failed to set Info field for $($User.Name) - $_"   
                        }   
                    }   
                try {   
                    Disable-ADAccount -Identity $UserName -ErrorAction Stop   
                    Write-LogFile -LogData "$($User.Name) successfully disabled"   
                    }   
                catch {   
                    Write-LogFile -LogData "Error - Failed to disable AD Account $($User.Name) - $_"   
                    }   
                }   
            $TriggeredUsers += $User | Select Name,SamAccountName,LastLogonDate,Info  
            }    
        }   
    }   

$TriggeredUsers | Format-Table   
$TriggeredUsers | Export-Csv $TriggeredPath -NoTypeInformation -Append  
Windows for business | Windows Server | User experience | PowerShell
{count} votes

5 answers

Sort by: Most helpful
  1. Rich Matheisen 47,901 Reputation points
    2021-07-30T01:38:04.487+00:00

    It looks like your problem is in these lines (I've added the missing "_" character -- see my previous comment about using the "Code Sample" editor):

    if ($UpdateInformation -ne $null) {
                        $Info = Get-ADUser $UserName -Properties info | Where-Object { $_.info }
                        $Info += " $UpdateInformation - $Date"
    

    You're setting the $Info variable to contain a user object. I expect your intention was to just update the "Info" property of the user. Tht would probably look like this:

    $Info.info += " $UpdateInformation - $Date"
    

    To avoid confusion, I'd rename the $Info variable to $UserToUpdate or something closer to what the variable contains (even calling it "$x" and then updating "$x.info" would be less misleading).


  2. Anonymous
    2021-07-30T09:52:34.213+00:00

    Hi,

    The $info variable in Line 53 is of type [Microsoft.ActiveDirectory.Management.ADUser]. To update the notes you can use the info property.

    $Info = (Get-ADUser $UserName -Properties info).info  
    $Info += " $UpdateInformation - $Date"  
    

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  3. Rich Matheisen 47,901 Reputation points
    2021-07-30T19:14:17.597+00:00

    Let's try that in a slightly different way without the "Addition" operator:

    if ($UpdateInformation -ne $null) { 
                         $Info = Get-ADUser $UserName -Properties info | Where-Object {$_.info} 
                         $Info.info = "$($Info.info) $UpdateInformation - $Date" 
    

  4. Airlenn 1 Reputation point
    2021-08-01T23:44:39.553+00:00

    Hi All,

    Not sure if we are allowed to post links here, but.
    Do you think it's related to trying to add multiple values?

    https://social.technet.microsoft.com/Forums/en-US/064800b5-9836-4f7b-a26b-d7676acea8ee/add-more-than-one-value-in-info-attribute-active-directory?forum=ITCG

    0 comments No comments

  5. Rich Matheisen 47,901 Reputation points
    2021-08-02T02:44:29.507+00:00

    This works:

    $Username = "XXX"
    $UpdateInformation = "Disabled"
    $Date = Get-Date
    
    # set Info to something
    $Info = get-aduser -Identity $Username -Properties info
    $Info | Set-ADUser -replace @{info="1st info"}
    
    # get the user
    $Info = get-aduser -Identity $Username -Properties info | Where-Object {$_.info}
    $NewInfo = "{0};{1} - {2}" -f $Info.info, $UpdateInformation, $Date
    try { 
        Set-ADUser -Identity $UserName -Replace @{info=$NewInfo} -ErrorAction Stop 
    }
    Catch
    {
        $_
    }
    

    You can try replacing the ";" with "rn" when loading the $NewInfo variable, but I'm not sure how it might be handled when displayed in a property page in, say, ADUC.

    You should work on line #53 in your script, though. If there's no "info" the Where-Object won't return anything and the empty $Info variable will cause problems on line 54.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.