如何在Powershell中从Get-ADuser cmdlet输出中排除多个用户?

时间:2019-06-28 15:17:35

标签: powershell filter active-directory

我正在尝试导出特定办公室中用于外部访客签到系统的所有用户的列表。除了不将某些用户(大约20个左右)添加到公共目录外,我需要将它们从输出中排除。

这是我到目前为止所拥有的...

class ViewController: UIViewController {

    let customObject = CustomObject(frame: .init(x: 0, 
                                                 y: 0, 
                                                 width: 200.0, 
                                                 height: 200.0))

    let stackView: UIStackView = {
        let sv = UIStackView()
        sv.axis = .horizontal
        return sv
    }() 

    override func viewDidLoad() {
        super.viewDidLoad()

        let label = UILabel()
        label.text = "first Element in horizontal stackView"
        stackView.addArrangedSubview(label)

        addCustomObjectToStackView()
    }

    func addCustomObjectToStackView() {

        stackView.addArrangedSubview(customObject)

        UIView.animate(withDuration: 1.0, animations: {
            customObject.layoutIfNeeded()
        })
    }
}

例如,我希望避免使用较长的过滤线...

    Get-ADUser -Filter {City -eq "Dallas"} -Properties GivenName, Surname, EmailAddress, Name |
        Select GivenName, Surname, EmailAddress, Name | 
        Sort-Object -Property GivenName | 
        Export-Csv $env:USERPROFILE\Desktop\ADusers.csv -NoTypeInformation -Force

理想情况下,我想创建一个列出指定用户的变量。这样一来,我以后就可以轻松进行修改。

-filer {(name -ne "name 1")(name -ne "name 2")...} etc 

结果符合预期(需要排除的用户除外)...

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

假设没有自定义属性或其他方法可以识别这些用户/已经在ActiveDirectory中对其进行区分,那么您可以做的一件事就是从名称数组中构建过滤器字符串

$excluded = "Name 1","Name 2","Name 3","Name 4"
$namefilter = ($excluded | ForEach-Object{"name -ne '$_'"}) -join " -and " 
$cityfilter = "City -eq 'Dallas'"
Get-ADUser -Filter ($cityfilter, $namefilter -join " -and ") -Properties GivenName, Surname, EmailAddress, Name

所以过滤器实际上是这样的:

City -eq 'Dallas' -and name -ne 'Name 1' -and name -ne 'Name 2' -and name -ne 'Name 3' -and name -ne 'Name 4'

它看起来有些令人费解,但是$cityfilter, $namefilter -join " -and "允许在不更改代码的情况下丢失其中一个过滤器。因此,如果$excluded最终为空,则代码仍将成功。您可以轻松地做到这一点,但这是我想缓解的问题。