Error messages while executing script using remote session

Hi,

I have this script that is working perfectly when I run it on a on prem AD server without using the ps session.
when I run it locally using ps-session I get the below mentioned errors please advice.

[pre]

#select CSV file that contains the people where the groups needs to be removed
#csv file needs to be a comma separated file
$users = import-csv c:\temp\Csv\toRemove.csv
$date= Get-Date -Format “yyyy-MMM-dd”
$lastworkdate = (get-date).AddDays(-1).ToString(“yyyy-MMM-dd”)
$DisabledOU = “OU=Disabled,OU=Regions,DC=mydomain,DC=com”

$adServer = “cfdc01.mydomain.com

$cred = Import-Clixml -Path “${env:\userprofile}\paul.Cred”
#sessions
$ADsession = new-PSSession -computername $adServer -Credential $cred
Import-PSSession -Session $ADsession -Module ActiveDirectory -AllowClobber

foreach ($user in $users)
{
$manager = $null
#get manager
$manager = (get-aduser (get-aduser $user.SamAccountName -Properties manager).manager).Name

#get all the groups this user is medpsmber of an paste this in Note section
$groups =Get-ADPrincipalGroupMembership $user.SamAccountName

Set-ADUser $user.samAccountName -Replace @{info=$groups.name -join “rn”}

Set-ADUser $user.SamAccountName -Replace @{info = $groups.name -join ‘;’}

#remove department and Manager from user Add description and disable account
set-aduser $user.SamAccountName -clear manager, department
set-aduser $user.SamAccountName -Description $description
get-ADUser $user.SamAccountName | Disable-ADAccount
$description = “Disabled by Username.adm on " + $date +” Last workingday " + $lastworkdate + " Manager: "+ $manager

#add date to extension attribute nr15
Set-ADUser –Identity $user.SamAccountName -add @{‘extensionattribute15’=(Get-Date).ToString(“yyyy-MMM-dd”)}

$adgroups = Get-ADPrincipalGroupMembership -Identity $user.SamAccountName
foreach ($singlegroup in $adgroups)
{ # removing all groups except the domain user group pay attention a given group as also 1 samaccountname
if ($singlegroup.SamAccountName -notlike “Domain Users”)

if ($singlegroup.SamAccountName -notlike “Domain Users” -and $singlegroup.SamAccountName -notlike “syncedToAzure”)

{
Remove-ADPrincipalGroupMembership -Identity $user.SamAccountName -MemberOf $singlegroup.SamAccountName -confirm:$false

}

}
#move user to disabled
get-aduser $user.SamAccountName | move-adobject -targetpath $DisabledOU

$user = $null
}
[/pre]

the errors that I get are these
[pre]
Cannot validate argument on parameter ‘Identity’. The argument is null. Provide a valid value for the argument, and then try running the command again.

  • CategoryInfo : InvalidData: (:slight_smile: [Get-ADUser], ParameterBindingValidationException
  • FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser
  • PSComputerName : cfdc01.mydomain.com

The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of
the parameters that take pipeline input.

  • CategoryInfo : InvalidArgument: (CN=Aaron …,DC=com:PSObject) [Disable-ADAccount], ParameterBindingException
  • FullyQualifiedErrorId : InputObjectNotBound,Microsoft.ActiveDirectory.Management.Commands.DisableADAccount
  • PSComputerName : cfdc01.mydomain.com

Multiple values were specified for an attribute that can have only one value

  • CategoryInfo : NotSpecified: (user:ADUser) [Set-ADUser], ADException
  • FullyQualifiedErrorId : ActiveDirectoryServer:8321,Microsoft.ActiveDirectory.Management.Commands.SetADUser
  • PSComputerName : cfdc01.mydomain.com

The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties do not match any of
the parameters that take pipeline input.

  • CategoryInfo : InvalidArgument: (CN=Aaron …,DC=com:PSObject) [Move-ADObject], ParameterBindingException
  • FullyQualifiedErrorId : InputObjectNotBound,Microsoft.ActiveDirectory.Management.Commands.MoveADObject
  • PSComputerName : cfdc01.mydomain.com
    [/pre]
    Weird thing is that most of the script is executed correctly but the actual disabling account is not happening.

Paul

Are you running this whole script in the remote session? Does c:\temp\Csv\toRemove.csv exist on the remote machine?

Hi Doug

even when the file is placed on the remote machine it still gives me the same error

as mentioned it does 99% of the job as it should only the disabling does not seem to work

 

Paul

I managed to reduce the nr of errors to 1
the only thing I get an error on is set-ADUser but all the things that I modify on the given account are executed.

in this part I modified my script "changed line 4 into line 5
[pre]

set-aduser $user.SamAccountName -clear manager, department
set-aduser $user.SamAccountName -Description $description
#get-ADUser $user.SamAccountName | Disable-ADAccount
Disable-ADAccount -Identity $user.SamAccountName
[/pre]

and in order to move the user from current location to the disabled folder I changed the first line into the second line
[pre]
#get-aduser $user.SamAccountName | move-adobject -targetpath $DisabledOU
Move-ADObject -Identity (Get-ADUser $user.SamAccountName ).objectguid -TargetPath $DisabledOU -ErrorAction Continue -Confirm:$false

[/pre]

I just would like to understand the error message about the ad user and how to solve that
this is the remaining message

[pre]
Multiple values were specified for an attribute that can have only one value

  • CategoryInfo : NotSpecified: (Username:ADUser) [Set-ADUser], ADException
  • FullyQualifiedErrorId : ActiveDirectoryServer:8321,Microsoft.ActiveDirectory.Management.Commands.SetADUser
  • PSComputerName : cfdc01.mydomain.com
    [/pre]

Paul

in addition when I run the set-aduser seperately they are executed correctly without any error messages
is there a way to group this in one single line?
something like set-ADuser $user.SamAccountName

-clear manager department

-description $description

-add -add @{‘extensionattribute15’=(Get-Date).ToString(“yyyy-MMM-dd”)}

or would this not make any difference?

Instead, can you try using Invoke-Command instead of implicit remoting.

@kvprasoon,

you mean something like

invoke-command -session $Adsession -scriptblock {}
and put everything in the scriptblock?

any reason why you prefer the invoke command above implicit remoting?

[quote quote=223182]Instead, can you try using Invoke-Command instead of implicit remoting.

[/quote]

[quote quote=223182]Instead, can you try using Invoke-Command instead of implicit remoting.

[/quote]
if I use the invoke command nothing works

Paul

I don’t have a system to test, so I’m guessing, the manager property via implicit remoting is returning null in below expression

(get-aduser $user.SamAccountName -Properties manager).manager

this is returning the correct value

PS C:\WINDOWS\system32> $manager = (get-aduser (get-aduser $user.SamAccountName -Properties manager).manager).Name

PS C:\WINDOWS\system32> $manager
Stijn …
individually everything works I’ve been testing this but for some reason running all together giving me the above message and everything is executed as required.
However I would like to run this without any messages and trying to understand why I get this message and on top of that solve it so that I don’t have it anymore

 

There are multiple GETs on user and group and the SET commands don’t need to be run separately. Also, you define an AD controller, but no every command has it as a parameter so it’s going to hop all over the place. Take a look at this code. One GET, one SET and started some error handling:

$users = import-csv c:\temp\Csv\toRemove.csv
$date= Get-Date -Format “yyyy-MMM-dd”
$lastworkdate = (get-date).AddDays(-1).ToString(“yyyy-MMM-dd”)
$DisabledOU = “OU=Disabled,OU=Regions,DC=mydomain,DC=com”

$adServer = “cfdc01.mydomain.com”

$cred = Import-Clixml -Path “${env:\userprofile}\paul.Cred”
#sessions
$ADsession = new-PSSession -computername $adServer -Credential $cred
Import-PSSession -Session $ADsession -Module ActiveDirectory -AllowClobber

foreach ($user in $users) {

    $adUser = Get-ADUser -Filter {SamAccountName -eq $user.SamAccountName} -Server $adServer -Properties Manager
    
    if ($adUser) {
        if ($adUser.Manager) {
            $manager = Get-ADUser -Identity $adUser.manager -Server $adServer  | 
                       Select-Object -ExpandProperty Name
        }
        else {
            'No manager defined for {0}' -f $adUser.SamAccountName
        }
        
        $groups = Get-ADPrincipalGroupMembership -Identity $adUser -Server $adServer

        try {
            $setParams = @{
                Identity    = $adUser
                Replace     = @{info = $groups.name -join ‘;’}
                Clear       = 'manager', 'department'
                Add         = @{‘extensionattribute15’=(Get-Date).ToString(“yyyy-MMM-dd”)}
                Description = $description
                Server      = $adServer
                ErrorAction = Stop
            }

            Set-ADUser @setParams
            Disable-ADAccount -Identity $adUser -Server $adServer -ErrorAction Stop
        }
        catch {
            'Problem setting stuff on {0}. {1}' -f $adUser.SamAccountName, $_
        }

        foreach ($singlegroup in ($adgroups | Where{$_.SamAccountName -notlike “*Domain Users*”})) {
            #Need try\catch
            Remove-ADPrincipalGroupMembership -Identity $adUser -MemberOf $singlegroup.SamAccountName -Server $adServer -Confirm:$false -ErrorAction Stop
        }

        #Need try\catch
        Move-ADObject -Identity $adUser -TargetPath $DisabledOU -Server $adServer -ErrorAction Stop
    }
    else {
        'User {0} not found on dc {1}' -f $user.SamAccountName, $adServer
    }
}

Hi Rob,

thanks for your time to write this down really appreciated. I get however an error on this line

[pre]
$adUser = Get-ADUser -Filter {SamAccountName -eq $user.SamAccountName} -Server $adServer -Properties Manager
[/pre]
[pre]
Variable: ‘user’ found in expression: $user.SamAccountName is not defined.

  • CategoryInfo : InvalidArgument: (:slight_smile: [Get-ADUser], ArgumentException
  • FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUser
  • PSComputerName : cfdc01.mydomain.com
    [/pre]
    when I request the content of $user.SamAccountName I do get as result “Paul”

when I just run the above mentioned ADuser … I get the same error message as above

Please advice

Paul

Try it like this:

$samAccountName = $user.SamAccountName
$adUser = Get-ADUser -Filter {SamAccountName -eq $SamAccountName} -Server $adServer -Properties Manager

Unfortunately same result
$User results in
SamAccountName email DISPLAY NAME active


Paul Paul@mydomain.com Paul+lastname True

$SamAccountName = Paul

error message

[pre]
Variable: ‘SamAccountName’ found in expression: $SamAccountName is not defined.

  • CategoryInfo : InvalidArgument: (:slight_smile: [Get-ADUser], ArgumentException
  • FullyQualifiedErrorId : ActiveDirectoryCmdlet:System.ArgumentException,Microsoft.ActiveDirectory.Management.Commands.GetADUser
  • PSComputerName : cfdc01.mydomain.com
    [/pre]

 

Booted up my demo VM…works for me…

PS C:\Users\Administrator> 
$users = [pscustomobject]@{
    Name = 'Rob'
    SamAccountName = 'rs'
}

foreach ($user in $users) {
    $samAccountName = $user.SamAccountName
    $adUser = Get-ADUser -Filter {SamAccountName -eq $SamAccountName} -Properties Manager

}

PS C:\Users\Administrator> $adUser


DistinguishedName : CN=Rob Simmers,OU=Technology,OU=Demo,DC=DEMO,DC=LOCAL
Enabled           : True
GivenName         : Rob
Manager           : 
Name              : Rob Simmers
ObjectClass       : user
ObjectGUID        : ff13f281-367d-461c-b620-a65712c8d3b1
SamAccountName    : rs
SID               : S-1-5-21-1674595758-692476252-3278724153-1103
Surname           : Simmers
UserPrincipalName : rs@DEMO.LOCAL

Rob,
I agree that it works when you run it straight on your AD server I’m pretty sure that it has something to do with the PSSession.

Paul

 

Paul, is this not just a double hop issue?

weird thing is that the orginal code

[pre]
#get manager
$manager = (get-aduser (get-aduser $user.SamAccountName -Properties manager).manager).Name
[/pre]
ran today without throwing any errors.
I’m still learning to improve my powershell skills and would like to use Rob’s proposed solution since my script is just a 1.0 version so to speak and needs improvement on logging stuff

this script is just 1 part of the total offboarding tasks that I’m currently doing

Ideally I would like to create a separate script that is going to check :
if the folders exist

if the required files exist
to check and setup the different sessions I need.

the second script

is going to hide all users from the Global address list

the next script is this one that is the above one to perform the offboarding tasks

the last one is to remove all the groups a user is Member of through AzureAD

and using 1 ps file to call all different scripts in the required order especially for the AzureAD script since there is a 30 min delay due to syncing between on prem AD and AzureAD

I’m happy to share what I have sofar and also happy to get feedback on how to improve my code where needed

Just try it, if it don’t work you can rule it out.

$TargetServer = 'Target'

# configure the computer you directly connect to
$null = Invoke-Command -ScriptBlock {
Enable-WSManCredSSP -Role Server -Force | Out-String
} -ComputerName $TargetServer

# establish CredSSP trust
$null = Enable-WSManCredSSP -Role Client -DelegateComputer $TargetServer -Force

Invoke-Command -ComputerName $TargetServer -ScriptBlock {
script.ps1
} -Credential (Get-Credential -Message "Your admin credentials") -Authentication Credssp

This article explains it exactly.

CredSSP not allowed on our domain