如何使用管道将变量传递到 Write-Host

How to pass variables into Write-Host with 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 }
}

任何人都可以提出一种实现此目的的方法,同时仍保持第一个示例的简洁格式吗?

你将不得不在某些时候使用某种 iteration/indexing 来实现这一点,其中包含 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