Search code examples
powershellcmdactive-directorydsquery

Using cmd pipe in the powershell Invoke-Expression


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?


Solution

  • 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