question

Airlenn avatar image
0 Votes"
Airlenn asked RichMatheisen-8856 edited

Disable AD user powershell script error

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-server-powershell
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

If you're going to include code, please use the "Code Sample" editor. It's the icon with "101 010" on it, it's 5th from the left. You can also activate it using Ctrl-K.

Separating code from text is error-prone. In addition, the text editor turn the string "$<underbar>" into just "$", and you may get "smart quotes" instead of "straight quotes", and hyphens turned into en-dashes.

0 Votes 0 ·
Airlenn avatar image Airlenn RichMatheisen-8856 ·

Thanks RichMatheisen-8856
Just put the code in the editor
Sorry i'm new to posting here

0 Votes 0 ·
RichMatheisen-8856 avatar image
0 Votes"
RichMatheisen-8856 answered RichMatheisen-8856 edited

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 "`r`n" 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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Airlenn avatar image
0 Votes"
Airlenn answered

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

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

RichMatheisen-8856 avatar image
0 Votes"
RichMatheisen-8856 answered Airlenn commented

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" 
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Tried ....

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

Same error as before/above.

0 Votes 0 ·
IanXue-MSFT avatar image
0 Votes"
IanXue-MSFT answered Airlenn commented

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.

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Tried

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

Same error as above

0 Votes 0 ·
RichMatheisen-8856 avatar image
0 Votes"
RichMatheisen-8856 answered Airlenn commented

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).

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

I made the the change

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

But still getting the error

 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
0 Votes 0 ·