Search code examples
powershellstart-job

Using Get-ADPrincipalGroupMembership as a job


I want to get the AD Group Membership as a job. Just using

Get-ADPrincipalGroupMembership -Identity $objUser.DistinguishedName

nicely returns a list of the AD-groups. However when I try this as a job:

$Job = Start-Job {Get-ADPrincipalGroupMembership $objUser.DistinguishedName}
$Job.Name
Wait-Job -Name $Job.Name
Receive-Job -Name $Job.Name

I get an error:

Cannot validate argument on parameter 'Identity'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again. + CategoryInfo : InvalidData: (:) [Get-ADPrincipalGroupMembership], ParameterBindingValidationExcep
tion + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.Get ADPrincipalGroupMembership + PSComputerName : localhost What am I doing wrong?


Solution

  • Jobs are running in the background and not in the current scope, so The Start-Job doesn't know anything about your variables, unless you tell it about them.

    $DN = $objUser.DistinguishedName
    $Job = Start-Job {Get-ADPrincipalGroupMembership $args[0]} -ArgumentList $DN
    $Job.Name
    Wait-Job -Name $Job.Name
    Receive-Job -Name $Job.Name
    

    Explanation:

    Add your variables with the -ArgumentList $var1,$var2 parameter then use the $args[0] for the first parameter $args[1] to the 2nd and so on.

    In your case only one parameter is needed, so use -ArgumentList $DN and call it with $args[0] inside the start-job ScriptBlock