I have a script that I have been working on, and I make it so far then it fails:

I am looking for the script to import a CSV that has three fields: Username,EmployeeID,UserPrincipalName

The file is called users.csv

Items the script is supposed to accomplish

Disable the Account
Reset PWD
Expire the account to todays date
Clear all groups except Domain Users
APPEND the description filed with text
Move the account to the Terminated OU

Then the script goes to 0365 items

Remove all 0365 Licences
Check to see if the account is on litigation hold - if the true move to the next line if False set a 720 hold
Remove from GAL

## This portion of the script is AD
##Please change your path for the file locations 
##
$NewPWD = "WeLightTheWay007!"
Import-Module ActiveDirectory ##Import AD module to run AD commands from Powershell 
$UsersToDIsable=Import-Csv -Path C:\scripts\Users.csv ## Import the CSV into a variable object for ease of use
ForEach ($UserToDisable in $UsersToDisable) 
{
    $User = $UserToDisable.UserName
    Disable-ADAccount -Identity $User #Disables the user in AD
    Set-ADAccountPassword -Identity $User -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $NewPWD -Force) #Sets Password to the value of $NewPWD
    $expire = Get-Date #Set Today's date as Expiration date.
    Set-ADAccountExpiration -Identity $User -DateTime $expire
    #Get all Groups the user is a member of
    $Groups = Get-ADUser -Identity $User -Properties MemberOf
    # Remove all group memberships (will leave Domain Users as this is NOT in the MemberOf property returned by Get-ADUser)
    foreach ($group in $Groups)
        {
            Remove-ADGroupMember -Identity $group -Members $User
        }
    #Set User's Description
    Get-ADUser $User -Properties Description | ForEach-Object { Set-ADUser $_ -Description "$($_.Description)Part of AD Cleanup Project: $(Get-Date -Format 'MM-dd-yyyy') by ${env:UserDomain}\${env:UserName}" }
    Get-ADUser -Identity $User | Move-ADObject –TargetPath "OU=Terminated,OU=CORPORATE,OU=ALG Users,DC=XXXX,DC=com" ###### CHANGE THIS TO MATCH YOUR OUs DN!!
}

#############I KNOW THE SCRIPT WORK TO HERE

##This Portion of the scripts is O365 and uses the UPN Filed in the csv file
#This portion removes all 0365 Licence

ForEach ($user in $Users)
{
    $User = Get-MsolUser -UserPrincipalName $_.UserPrincipalName
    $Skus = $User.licenses.AccountSkuId
    Set-MsolUserLicense -UserPrincipalName $User.UserPrincipalName -RemoveLicenses $Skus
    }

##This portion is For Litigation Hold

ForEach ($user in $Users)
{
   
    if ($user.LitigationHoldEnabled -eq $false)
    {
        Set-Mailbox -identity $User -LitigationHoldEnabled:$true -LitigationHoldDuration 730
    }
   
}

##This portion removes user from GAL

ForEach ($user in $users)
{
 Set-MailContact -Identity $user -HiddenFromAddressListsEnabled $true
 }
4 Spice ups

would be nice if you can elaborate what fails and where in the script and possibly the error message?

1 Spice up

I dont get a message for the portions that are not happening:

It does not remove the 0365 licences

It does not do the litigation hold

It does not hide from Gal

They only Error is below - and thats because there are no groups associated with this user - which is fine.

So is the Script just stopping after that error?

Remove-ADGroupMember : Cannot find an object with identity: ‘CN=Acuity, XXXX=Terminated,OU=CORPORATE,OU=ALG Users,DC=XXX,DC=com’ under: ‘DC=XXX,DC=com’.
At C:\scripts\Non-AutomatedScript-REVB.ps1:19 char:13

  • Remove-ADGroupMember -Identity $group -Members $User
  • CategoryInfo : ObjectNotFound: (CN=Acuity, fXXXup,DC=com:ADGroup) [Remove-ADGroupMember], ADIdentityNotFoundException
  • FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.RemoveADGroupMember

Try this:

ForEach ($user in $Users)
{
    $User = Get-MsolUser -UserPrincipalName $_.UserPrincipalName
    $Skus = $($User.licenses).AccountSkuId
    Set-MsolUserLicense -UserPrincipalName $User.UserPrincipalName -RemoveLicenses $Skus
    }

Nope - and no error?

I think I might know what I did wrong…

ForEach ($user in $Users)
{
    $User = Get-MsolUser -UserPrincipalName $_.UserPrincipalName
    $Skus = $($User.licenses).AccountSkuId
    
    ForEach ($s in $Skus){
        Set-MsolUserLicense -UserPrincipalName $User.UserPrincipalName -RemoveLicenses $s
    }
}

Nope and no errors

Does it have to do with how I am calling the User Account ?

The Active Directory portion uses the Username from the csv file and the 0365 uses the UPN

Do I have me variables messed up?

Well, can you break it down?

$User = Get-MsolUser -UserPrincipalName $user.UserPrincipalName
$Skus = $($User.licenses).AccountSkuId

Does user have a value?

Are there the right skus in the the $skus variable?

before you do the foreach you want to manually confirm all the stuff.

If you manually type in the data, does it work then?

I have no access to o365 so I can’t test this for you.

Yep, that was the final part: You never actually filled the $users array. It’s the $UsersToDisable array

ForEach ($user in $UsersToDisable) 
{
    $User = Get-MsolUser -UserPrincipalName $_.UserPrincipalName
    $Skus = $($User.licenses).AccountSkuId
    
    ForEach ($s in $Skus){
        Set-MsolUserLicense -UserPrincipalName $User.UserPrincipalName -RemoveLicenses $s
    }
}

In addition, there is one group in AD that a user cannot be removed from. It’s the Domain Users group. You should be seeing errors with that one.

1 Spice up

@alexw ​ - yes if I run it by itself pulling from the csv it worked

@shelly - The script really fails with that - I believe because the 0365 portion needs to pull from the CSV the column that is labeled UserPrincipalName for the instead of the Username

Here are my errors:

Remove-ADGroupMember : Cannot find an object with identity: ‘CN=XXX, Joe Q.,OU=Terminated,OU=CORPORATE,OU=ALG Users,DC=XXX,DC=com’ under: ‘DC=XXX,DC=com’.
At C:\scripts\Non-AutomatedScript-REVB.ps1:19 char:13

  • Remove-ADGroupMember -Identity $group -Members $User
  • CategoryInfo : ObjectNotFound: (CN=Acuity, JoeXXX,DC=com:ADGroup) [Remove-ADGroupMember], ADIdentityNotFoundException
  • FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.RemoveADGroupMember

Get-MsolUser : Cannot bind argument to parameter ‘UserPrincipalName’ because it is null.
At C:\scripts\Non-AutomatedScript-REVB.ps1:34 char:45

  • $User = Get-MsolUser -UserPrincipalName $_.UserPrincipalName
  • CategoryInfo : InvalidData: (:slight_smile: [Get-MsolUser], ParameterBindingValidationException
  • FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.Online.Administration.Automation.GetUser

Cannot process argument transformation on parameter ‘Identity’. Cannot convert the “@{Username=XXXXX; EmployeeID=XXXXXX; UserPrincipalName=JXX@XXX.COM}” value of type
“Deserialized.System.Management.Automation.PSCustomObject” to type “Microsoft.Exchange.Configuration.Tasks.MailContactIdParameter”.

  • CategoryInfo : InvalidData: (:slight_smile: [Set-MailContact], ParameterBindin…mationException
  • FullyQualifiedErrorId : ParameterArgumentTransformationError,Set-MailContact
  • PSComputerName : o365exch1ccc.com
## This portion of the script is AD
##Please change your path for the file locations 
##
$NewPWD = "PWD"
Import-Module ActiveDirectory ##Import AD module to run AD commands from Powershell 
$UsersToDisable=Import-Csv -Path C:\scripts\users.csv ## Import the CSV into a variable object for ease of use
ForEach ($UserToDisable in $UsersToDisable) 
{
    $User = $UserToDisable.UserName
    Disable-ADAccount -Identity $User #Disables the user in AD
    Set-ADAccountPassword -Identity $User -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $NewPWD -Force) #Sets Password to the value of $NewPWD
    $expire = Get-Date #Set Today's date as Expiration date.
    Set-ADAccountExpiration -Identity $User -DateTime $expire
    #Get all Groups the user is a member of
    $Groups = Get-ADUser -Identity $User -Properties MemberOf
    # Remove all group memberships (will leave Domain Users as this is NOT in the MemberOf property returned by Get-ADUser)
    foreach ($group in $Groups)
        {
            Remove-ADGroupMember -Identity $group -Members $User
        }
    #Set User's Description
    Get-ADUser $User -Properties Description | ForEach-Object { Set-ADUser $_ -Description "$($_.Description)Part of AD Cleanup Project: $(Get-Date -Format 'MM-dd-yyyy') by ${env:UserDomain}\${env:UserName}" }
    Get-ADUser -Identity $User | Move-ADObject –TargetPath "OU=Terminated,OU=CORPORATE,OU=XXX Users,DC=FFF,DC=com" ###### CHANGE THIS TO MATCH YOUR OUs DN!!
}

#############I KNOW THE SCRIPT WORK TO HERE

##This Portion of the scripts is O365 and uses the UPN Filed in the csv file
#This portion removes all 0365 Licence

ForEach ($User in $UsersToDisable) 
{
    $User = Get-MsolUser -UserPrincipalName $_.UserPrincipalName
    $Skus = $($User.licenses).AccountSkuId
    
    ForEach ($s in $Skus){
        Set-MsolUserLicense -UserPrincipalName $User.UserPrincipalName -RemoveLicenses $s
    }
}

##This portion is For Litigation Hold

ForEach ($User in $UsersToDisable)
{
   
    if ($User.LitigationHoldEnabled -eq $false)
    {
        Set-Mailbox -identity $User -LitigationHoldEnabled:$true -LitigationHoldDuration 730
    }
   
}

##This portion removes user from GAL

ForEach ($User in $UsersToDisable)
{
 Set-MailContact -Identity $User -HiddenFromAddressListsEnabled $true
 }![Capture.jpg|500x141](upload://zNAAlI6SNbF8n6miHmbqz79SICj.jpeg)

Are your users in O365 signing in with their email address? If so, you’ll need to get that information into your csv.

They sign on with a SSO username - which is defined in the CSV as the UserPricipalName

can you share (sanitized) how your CSV looks like?

Remove-ADGroupMember : Cannot find an object with identity: ‘CN=XXX, Joe Q.,OU=Terminated,OU=CORPORATE,OU=ALG Users,DC=XXX,DC=com’ under: ‘DC=XXX,DC=com’.

So if you put that info in manually, it works? sounds like somewhere there is a disconnect?

I have attached a copy of the CSV - it has three columns

Username,EmployeeID,UserPricipalName

I think that portion of the error is because there are NO groups that this test user is apart of.

I am more concerned with the 0365 issues

Capture.jpg

Try not to re-use the same variable, makes things conpuzzling.

1 Spice up

I’ve done messed it up now.

Anyways thanks for your help.

I think the issue is my variables are all over the place and that we are hybrid - so having to login to both is confusing me.

I am still learning and need to sit back and look at what I’ve done because I have confused myself…