Phil
Phil

Reputation: 642

$env:USERNAME not defined when filtering on Get-ADuser?

Can anyone explain why this fails:

PS C:\Windows\system32> Get-ADUser -Filter {SamAccountName -eq $env:USERNAME}
Get-ADUser : Variable: 'env' found in expression: $env is not defined.

But this succeeds:

PS C:\Windows\system32> $u=$env:USERNAME

PS C:\Windows\system32> Get-ADUser -Filter {SamAccountName -eq $u}

DistinguishedName : CN<snip>

Is the above the most elegant workaround or am I missing something?

Upvotes: 0

Views: 908

Answers (2)

William Higgs
William Higgs

Reputation: 191

You know, this works too:

Get-aduser "$samaccountname"

or

Get-aduser "$env:USERNAME"

Don't even need to bother with "-Filter" if you are passing the samaccountname

Upvotes: 1

Daniel Bj&#246;rk
Daniel Bj&#246;rk

Reputation: 2507

This works:

$username = $env:USERNAME
Get-ADUser -Filter 'SamAccountName -eq $username'

And this works too:

Get-ADUser -Filter "SamAccountName -eq '$($env:USERNAME)'"

enter image description here

Upvotes: 1

Related Questions