Using cmd pipe in the powershell Invoke-Expression

321 Views Asked by At

I'm trying to get all the emails and usernames from the Active Directory from the specific Organization Unit using powershell. This is my code:

function Invoke-CmdCommand {
    Param(
        [parameter(position = 0)]
        $Cmd , 
        [parameter(position = 1)]
        $RunFolder = $PSScriptRoot
    )
    try {
        $cmdToRun = "cmd /c cd `"$RunFolder`" `"&`" $Cmd";
        Write-Host "$RunFolder> $Cmd";
        Invoke-Expression "& $($cmdToRun.Replace("^","^^"))";
    }
    catch {
        Write-Error "********** Function $($MyInvocation.MyCommand.Name) failed **********";
        Write-Error $_.Exception.Detail.InnerText;
        exit 1;
    }
}


$cmd = "dsquery user `"OU=Disabled Users,DC=microfinancial,DC=com`" -limit 10000 | dsget user -samid -email"

$test = Invoke-CmdCommand -Cmd $cmd

And I'm getting following error:

dsget failed:Value for 'Target object for this command' has incorrect format. type dsget /? for help.

What can I do?

2

There are 2 best solutions below

0
Gabriel Luci On BEST ANSWER

As pointed out in the comment above, you're much better off using Get-ADUser. This will get you an array of objects that just contain the username and email address:

Import-Module ActiveDirectory
Get-ADUser -Filter * -SearchBase "OU=Disabled Users,DC=microfinancial,DC=com" `
    -Properties SamAccountName,EmailAddress `
  | Select-Object SamAccountName,EmailAddress

If Import-Module ActiveDirectory doesn't work for you, then install RSAT (assuming you're on Windows 10): https://www.microsoft.com/en-ca/download/details.aspx?id=45520

Or if you're running this on a Server version of Windows:

Import-Module ServerManager
Add-WindowsFeature RSAT-AD-PowerShell
0
jrider On

If all you are trying to do is emails and usernames from Active Directory, Get-ADUser that is included in the ActiveDirectory module is the preferred route.

-SearchBase will allow you to scope the OU that you would like to start with. You will need to specify what properties you would like to include in Get-ADUser by using -Properites. The Select will show only the properties that you wish to use.

The following example will get all user's user names (samaccountname) and primary email:

Get-ADUser -filter * -Properties SamaccountName, mail -SearchBase "DC=domain,DC=local" | Select SamaccountName, Mail