1

I am trying to pass an object and a string variable to "Get-ADUser" commandlet using Invoke-Expression.

The credentials are built like this:

$secpasswd = ConvertTo-SecureString $pwd -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($uid, $secpasswd)

then a string is composed with additional parameters:

if ($dc)
{
    $newVar = " -server $dc"
}

if ($ou) 
{
    $newVar = $newvar + " -Serchbase $ou"
 }

and finally the following is executed

$AllADUsers = iex "Get-ADUser $newVar -Credential $($mycreds) -Filter * -Properties *"    | Where-Object {$_.info -NE 'Migrated'}

but it brings up the credential dialog and an error if i just click ok

Get-ADUser : Cannot validate argument on parameter 'Credential'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again. At line:1 char:54 + Get-ADUser -server srv-v-hh001.bwg.corp -Credential System.Management.Automatio ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser

I think this is because iex is parsing $mycreds as a string, is there a way to tell Powershell this is an object?

1

1 Answer 1

0

Why do you need IEX at all? Use hashtable to build parameters for Get-ADUser and then just splat it:

$secpasswd = ConvertTo-SecureString $pwd -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($uid, $secpasswd)

$Splat = @{
    Credential = $mycreds
    Filter = '*'
    Properties = '*'
}

if ($dc)
{
    $Splat.Server = $dc
}

if ($ou) 
{
    $Splat.SearchBase = $ou
}

$AllADUsers = Get-ADUser @Splat | Where-Object {$_.info -NE 'Migrated'}

BTW, you have a typo in your SearchBase parameter name.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that did it!