用于更新AD中用户的manager字段并将结果导出到CSV的PowerShell脚本

kzmpq1sx  于 2023-04-03  发布在  Shell
关注(0)|答案(1)|浏览(247)

首先,我只是一个PS学习者,请原谅我。
我已经设法调整了一个脚本(我仍然需要测试!),它将执行AD用户的管理器字段的批量更新。
使用用户的用户名和管理员的用户名,它将读取包含2个字段的CSV文件:员工用户名经理用户名

Import-Csv "C:\Users\Temp\UpdateManagers.csv" |
    ForEach-Object {
        $ADUser  =  Get-ADUser -Filter "sAMAccountName -eq '$($User.EmployeeUserName)'"
        $manager = (Get-ADUser -Filter "sAMAccountName -eq '$($User.'ManagerUserName')'").distinguishedname

        if ($ADUser -and $manager) {
            $ADUser | Set-ADUser -manager $manager
        }
    }

我的CSV格式是:

我想知道是否有人可以帮助我用我的脚本将结果输出到CSV文件,以说明在字段中更新了经理的用户的用户名和字段中的新经理用户名。

kkbh8khc

kkbh8khc1#

如果你想要输出错误/成功消息,我会将你的代码扩展为如下所示:

$result = Import-Csv "C:\Users\Temp\UpdateManagers.csv" |
ForEach-Object {
    $csvUser    = $_.EmployeeUserName  # for convenience
    $csvManager = $_.ManagerUserName
    # create an object to output
    $out = [PsCustomObject]@{User = $csvUser; NewManager = $null; Result = $null }

    if ([string]::IsNullOrWhiteSpace($csvManager)) {
        $out.Result = "Error: User does not have a manager specified in the csv"
        $out
        continue
    }

    $ADUser = Get-ADUser -Filter "sAMAccountName -eq '$csvUser'" -Properties Manager
    if ($ADUser) {
        $manager = Get-ADUser -Filter "sAMAccountName -eq '$csvManager'"
        if ($manager) {
            $out.NewManager = $manager.SamAccountName
            if ($manager.SamAccountName -ne $csvManager) {
                $ADUser | Set-ADUser -Manager $manager.DistinguishedName
                $out.Result = "Success: New manager '$($manager.SamAccountName)' set for this user"
            }
            else {
                $out.Result = "Skipped: Manager for this user was already correct"
            }
        }
        else {
            Write-Warning "Manager '$csvManager' does not exist"
            $out.Result = "Error: Manager '$csvManager' does not exist"
        }
    }
    else {
        Write-Warning "User '$csvUser' does not exist"
        $out.Result = "Error: User '$csvUser' does not exist"
    }
    # output the object so it gets collected in variable $result
    $out
}

# output result on screen
$result | Format-Table -AutoSize

# write result to csv file
$result | Export-Csv -Path 'X:\Somewhere\UpdateManagersResults.csv' -NoTypeInformation

相关问题