Link to home
Start Free TrialLog in
Avatar of Triforce2000
Triforce2000Flag for Belgium

asked on

Error handling Powershell

Hello All,

I've written a script ( just a beginner in Powershell ) for updating manager attribute in AD with a CSV of HR.
But, this CSV isn't up to date. I mean, some users or managers doesn't work anymore for our company.
So some users/managers doesn't exist or are disabled.
So I got errors in my powershell script.

My script:
 $users = import-csv  C:\Users\adm_velvnsar\Downloads\usersmanagers.csv

 ForEach ($user in $users) {
 $displaynameCSV = $user.Name
 $managerCSV = $user.Manager


$CurrentADUsersWithManager = Get-ADUser -filter {DisplayName -like $displaynameCSV} -properties * | Select-Object displayname,manager,SamAccountName 
$GetManagerSamAccountName = Get-ADUser -Filter {DisplayName -like $managerCSV} -Properties * | select-object SamAccountname


    If(!($CurrentADUsersWithManager.manager)) {
        If(!($GetManagerSamAccountName.SamAccountname)) {
            Set-ADUser $CurrentADUsersWithManager.SamAccountName -Manager $GetManagerSamAccountName.SamAccountname

      }
    }
 }

Open in new window


Maybe my script isn't written well, but it works..
But I want all users that doesn't exist anymore or disabled in a textfile, is it possible?
Avatar of Joseph Moody
Joseph Moody
Flag of United States of America image

You could use the $? variable. It holds a true/false value based on the last ran statement. You could use something like:

Set-ADUser $CurrentADUsersWithManager.SamAccountName -Manager $GetManagerSamAccountName.SamAccountname

if ($? -eq $false){$GetManagerSamAccountName.SamAccountname | out-file .\oldusers.txt -append}

Open in new window

Avatar of Triforce2000

ASKER

Doesn't work, It created a olduser.txt, but no names in in.
I know that around 20 people doesn't exist anymore like in the file..
Try this instead.

if ($? -eq $false){$CurrentADUsersWithManager.SamAccountName | out-file .\oldusers.txt -append}

Open in new window

Same.. File created, nothing in it..
Any other solutions?
ASKER CERTIFIED SOLUTION
Avatar of alohadin
alohadin

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
No comment has been added to this question in more than 21 days, so it is now classified as abandoned.

I have recommended this question be closed as follows:

Accept: alohadin (https:#a42307357)

If you feel this question should be closed differently, post an objection and the moderators will review all objections and close it as they feel fit. If no one objects, this question will be closed automatically the way described above.

Pber
Experts-Exchange Cleanup Volunteer