【问题标题】:Using cmd pipe in the powershell Invoke-Expression在 powershell Invoke-Expression 中使用 cmd 管道
【发布时间】:2018-10-23 15:22:14
【问题描述】:

我正在尝试使用powershell 从特定的Organization Unit 获取来自Active Directory 的所有电子邮件和用户名。这是我的代码:

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

我收到以下错误:

dsget 失败:“此命令的目标对象”的值不正确 格式。输入 dsget /?寻求帮助。

我能做什么?

【问题讨论】:

  • 您是否有理由不使用Get-ADUser 来完成此操作?
  • 是的,有。因为我没有意识到。谢谢:)
  • 总是一个很好的理由。看起来人们已经在为您发布解决方案了。

标签: powershell cmd active-directory dsquery


【解决方案1】:

正如上面评论中所指出的,您最好使用Get-ADUser。这将为您提供仅包含用户名和电子邮件地址的对象数组:

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

如果 Import-Module ActiveDirectory 不适合您,请安装 RSAT(假设您使用的是 Windows 10):https://www.microsoft.com/en-ca/download/details.aspx?id=45520

或者,如果您在 Windows 的服务器版本上运行它:

Import-Module ServerManager
Add-WindowsFeature RSAT-AD-PowerShell

【讨论】:

    【解决方案2】:

    如果您想要做的只是来自 Active Directory 的电子邮件和用户名,则包含在 ActiveDirectory 模块中的 Get-ADUser 是首选路由。

    -SearchBase 将允许您确定要开始使用的 OU 的范围。您需要使用-Properites 指定要包含在Get-ADUser 中的属性。 Select 将仅显示您希望使用的属性。

    以下示例将获取所有用户的用户名(samaccountname)和主电子邮件:

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

    【讨论】:

      猜你喜欢
      • 2014-12-24
      • 2011-07-16
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 2010-09-05
      • 1970-01-01
      • 2014-12-21
      相关资源
      最近更新 更多