当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] PowerShell:从文本文件添加 Active Directory 用户(批量)

作者:精品下载站 日期:2024-12-14 07:21:09 浏览:16 分类:玩电脑

PowerShell:从文本文件添加 Active Directory 用户(批量)


当谈到导入大量用户时,csv 是第一。但是文本文件呢?当然,您可以将文本文件的内容导出到 csv。但在本文中,我想直接从文本文件添加活动目录用户。

介绍

对于以下内容,我使用此文本文件。与电影《泵铁》中的人物相似纯属偶然?

[玩转系统] PowerShell:从文本文件添加 Active Directory 用户(批量)

我相信大多数管理员对此并不满意。大多数管理员将开始转换为 csv。但我会保持现状。

1.使用Split添加用户

这让我分裂了。什么叫分裂? Split 是一种 PowerShell 方法。 Split 可以帮助你分割一些东西。我们必须拆分我们的列表。我们需要一份名字和姓氏的列表。因此,我们必须告诉 PowerShell,在哪里进行拆分。我们想在空白位置分割。

例子 :

[玩转系统] PowerShell:从文本文件添加 Active Directory 用户(批量)

("Patrick Grünauer").Split(" ")

[玩转系统] PowerShell:从文本文件添加 Active Directory 用户(批量)

现在我们分别称呼它们。

$name=("Patrick Grünauer").Split(" ")
$name[0]
$name[1]

[玩转系统] PowerShell:从文本文件添加 Active Directory 用户(批量)

很酷的东西。这正是我们下一步所需要的。

我的文件由名字和姓氏组成。它与上面的文件相同。

[玩转系统] PowerShell:从文本文件添加 Active Directory 用户(批量)

下面的代码

  • 将列表分为名字和姓氏
  • 添加具有 UserPrincipalName(姓氏)、SamAccountName(姓氏)、全名(名字 + 姓氏)和 AccountPassword 的新 Active Directory 用户
  • 使每个用户
  • 将 ChangePasswortAtLogon 设置为 True
  • 显示发生了什么(详细参数)

开始了:

Get-Content C:\temp\users.txt | ForEach-Object {$Split = $_.Split(" "); $given=$Split[0]; $sur=$Split[1]; New-ADUser -GivenName $given -Surname $sur -Name ($given + " " + $sur) -UserPrincipalName (($sur + "@" + "$env:userdnsdomain")).ToLower() -SamAccountName ($sur).ToLower() -AccountPassword (ConvertTo-SecureString -AsPlainText "Passw00rd123" -Force) -Enabled $true -ChangePasswordAtLogon $true -Verbose}

[玩转系统] PowerShell:从文本文件添加 Active Directory 用户(批量)

[玩转系统] PowerShell:从文本文件添加 Active Directory 用户(批量)

分裂成功了。注意名字和姓氏。

[玩转系统] PowerShell:从文本文件添加 Active Directory 用户(批量)

所有用户均已启用并且登录名(UPN、SamAccountname)正确。

[玩转系统] PowerShell:从文本文件添加 Active Directory 用户(批量)

2.使用ConvertFrom-String(PowerShell 5.0及更高版本)

现在让我们转向更简单的解决方案。如果您坐在运行 PowerShell 5.0 及更高版本的服务器前面,则可以使用 ConvertFrom-String。了解 ConvertFrom-String 可以为您做什么:

Get-Content C:\temp\Users.txt | ConvertFrom-String

[玩转系统] PowerShell:从文本文件添加 Active Directory 用户(批量)

所以我们有 P1 和 P2。那太棒了。

Get-Content C:\temp\users.txt | ConvertFrom-String | ForEach-Object {New-ADUser -GivenName $_.P1 -Surname $_.P2 -Name ($_.P1 + " " + $_.P2) -UserPrincipalName (($_.P2 + "@" + "$env:userdnsdomain")).ToLower() -SamAccountName ($_.P2).ToLower() -AccountPassword (ConvertTo-SecureString -AsPlainText "Passw000rd123" -Force) -Enabled $true -ChangePasswordAtLogon $true -Verbose}

[玩转系统] PowerShell:从文本文件添加 Active Directory 用户(批量)

好东西。希望你也喜欢它。

享受文本文件的乐趣!

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯