如何使用管道

时间:2016-03-11 16:59:05

标签: powershell foreach active-directory pipeline

我有以下一点脚本:

try {
    Get-ADUser -Properties Department -Filter $Filter | Where-Object {$_.Department -eq $old} | Set-ADUser -Department $new
} catch { Write-Host "Error occured" -BackgroundColor Red -ForegroundColor Black }

将一组特定用户的部门更改为所选部门($new)。

我希望在每个用户更新后用Successfully updated [$user.Name]显示Write-Host,但我无法解决如何使用管道执行此操作的问题!

我设法使用foreach,但它看起来并不好:

$users = Get-ADUser -Properties Department -Filter $Filter | Where-Object {$_.Department -eq $old}
ForEach ($user in $users) {
    try{
        Set-ADUser $user -Department $new
        Write-Host "Department changed: "$user.Name -BackgroundColor Green -ForegroundColor Black
    } catch { Write-Host "Error occured" -BackgroundColor Red -ForegroundColor Black }
}

有人可以提出一种方法来实现这一点,同时仍然保持第一个例子的简洁格式吗?

1 个答案:

答案 0 :(得分:2)

你必须在某个时刻使用某种迭代/索引来实现这一点,内部有try / catchcatch块不是管道的一部分。

我可能会建议ForEach-Object而不是foreach

Get-ADUser -Properties Department -Filter $Filter | 
    Where-Object {$_.Department -eq $old} |
    ForEach-Object {
        $user = $_
        try{
            Set-ADUser $user -Department $new
            Write-Host "Department changed: "$user.Name -BackgroundColor Green -ForegroundColor Black
        } catch { Write-Host "Error occured" -BackgroundColor Red -ForegroundColor Black }
    }

或者,编写自己的函数来处理它,它接受管道输入:

function Set-MyUserDepartment {
[CmdletBinding()]
param(
    [Parameter(
        Mandatory = $true,
        ValueFromPipeline = $true,
        ValueFromPipelineByPropertyName = $true
    )]
    [String[]]
    $Name ,

    [Parameter(
        Mandatory = $true
    )]
    [String]
    $NewDepartment
)

    Process {
        foreach($user in $Name) {
            try{
                Set-ADUser $user -Department $NewDepartment
                Write-Host "Department changed: $user" -BackgroundColor Green -ForegroundColor Black
            } catch { Write-Host "Error occured" -BackgroundColor Red -ForegroundColor Black }
        }
    }
}

然后你可以很好地使用它:

Get-ADUser -Properties Department -Filter $Filter | 
    Where-Object {$_.Department -eq $old} |
    Set-MyUserDepartment -NewDepartment $new