Search code examples
powershellactive-directorypowershell-remoting

Command Get-ADUser -Filter doesn't work in PSSession


I'm doing a script for changing user account AD with a GUI. When selecting a user in a list, I want to show all the groups of which he is a member. For the order it is OK but in a PSSession the command does not work, the -Filter parameter does not recognize the variable

$SessionAD = New-PSSession -ComputerName $AD
Invoke-Command $SessionAD -Command {Import-Module ActiveDirectory}
Import-PSSession $SessionAD -Module ActiveDirectory

...

$var = $ListeUsers.SelectedItem
$GroupsMember = Get-ADUser -Filter {Name -like $var} -Property MemberOf |
                Select -ExpandProperty MemberOf |
                Get-ADGroup -Property MemberOf |
                Select Name
Error : La variable : « var » trouvée dans l’expression : $var n’est pas définie.
    + CategoryInfo          : InvalidArgument : (:) [Get-ADUser], ArgumentException
    + FullyQualifiedErrorId : La variable : « var » trouvée dans l’expression : $var n’est pas définie.,Microsoft.ActiveDirectory.Management.Commands.GetADUser
    + PSComputerName        : AD-01

With the code below the command runs fine, but I can not retrieve the values of the variable $GroupsMember:

Invoke-Command -Session $SessionAD -ArgumentList $var,$GroupsMember -ScriptBlock {
    Param($var, $GroupsMember)
    $GroupsMember = Get-ADUser -Filter {Name -like $var} -Property MemberOf |
                    Select -ExpandProperty MemberOf |
                    Get-ADGroup -Property MemberOf |
                    Select Name
}

Solution

  • Finally found a solution to your problem. In your code the braces in Get-ADuser -Filter{...} are the problem.

    you can update your code like that :

    $SessionAD = New-PSSession -ComputerName "SVADDS01.Mylab.local"
    Invoke-Command $SessionAD -Command {Import-Module ActiveDirectory}
    Import-PSSession $SessionAD -Module ActiveDirectory | Out-Null
    
    $ADUSers = Get-ADuser -Filter *
    $var = $ADUSers | Select-Object -Property Name, SamaccountName | Out-GridView -OutputMode Single 
    
    $GroupsMember = Get-ADUser -Filter ('Name -eq "' + $var.Name + '"') -Property MemberOf |
                    Select -ExpandProperty MemberOf |
                    Get-ADGroup -Property MemberOf |
                    Select Name
    
    $GroupsMember
    Get-PSSession | Remove-PSSession
    

    Note that in the current solution :

    • My $var object contains an instance of a Get-ADUser object. this is the reason why I'm using $var.Name in the search
    • the Get-ADUser use, like you, a Filter but this one is a String built from the previous selection