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

[玩转系统] 使用 powershell 从 csv 批量导入设置过期日期

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

使用 powershell 从 csv 批量导入设置过期日期


使用 powershell 从 csv 批量导入设置过期日期

在许多公司中,您可以找到公司中不再使用但仍处于活动状态的用户帐户。一个好的选择是为帐户提供到期日期。为此我开发了一个小脚本。首先,这是一个命令,用于获取 CSV 文件输出中的所有帐户,并且已经具有到期日期。
当然,“Search-Base”参数必须适应相应的 OU 结构!

Get-ADUser -Filter * -SearchBase "OU=DEMO,DC=demo01,DC=it-koehler,DC=com" -Properties AccountExpirationDate | Select-Object Surname,Givenname,AccountExpirationDate |Export-Csv -Path C:\Temp\expdate-list.csv -Force -Encoding UTF8

[玩转系统] 使用 powershell 从 csv 批量导入设置过期日期

现在,人力资源人员或其他部门可以维护此 CSV 文件以及员工的离职日期。
现在这里是脚本,它读取 CSV 文件并使用此信息来设置帐户的到期日期。
注意:如果 CSV 中没有设置日期,用户将删除现有的到期日期!

在脚本中,必须调整两个变量“$OU”和“$CSVPATH”,其中OU是要搜索的OU的可分辨名称。

#import activedirecory module 
Import-Module ActiveDirectory
#import csv file 
$csvpath = "C:\temp\expdate-list.csv"
$users = Import-Csv -Path "$csvpath" -Encoding UTF8
$ou = "OU=DEMO,DC=demo01,DC=it-koehler,DC=com"
Write-Host "following users will be changed: " -ForegroundColor Gray
foreach($user in $users )
{
 $surname = ($user).Surname 
 $givenname = ($user).GivenName 
 $expdate = ($user).AccountExpirationDate 
 #check if date is not empty
 if($expdate -ne "$null"){
 get-aduser -Filter {(GivenName -eq $givenname) -and (Surname -eq $surname)} -SearchBase "$ou" | Set-ADUser -AccountExpirationDate $expdate
 Write-Host "expirationdate for user $givenname,$surname set to $expdate" -ForegroundColor Green
 }
 else {
 get-aduser -Filter {(GivenName -eq $givenname) -and (Surname -eq $surname)} -SearchBase "$ou" | Set-ADUser -AccountExpirationDate $null
 Write-Host "expirationdate deleted for: $givenname,$surname " -ForegroundColor Yellow
  }
 }
#show overview 
Write-Host " "
Write-Host "overview:"
Get-Aduser -Filter * -SearchBase "$ou" -Properties AccountExpirationDate | Sort-Object surname | Select-Object Surname,Givenname,AccountExpirationDate

此脚本还可以在域控制器上的 ISE 内运行。或者直接在 Powershell 控制台内。
当然,这个是可以扩展和调整的。然而,对于我的目的来说,这最初就足够了。

欢迎提出改进建议。
玩得开心。

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

取消回复欢迎 发表评论:

关灯