2017-06-15 48 views
0

我正在使用Power Shell腳本來創建Active Directory中的批量用戶。正如前一篇文章中所述,我對Power Shell相當陌生,並且希望在我接觸任何東西之前保持安全。下面是腳本,其中一些借用。它將從Import-CSV cmdlet中記錄的.csv中讀取數據。理想情況下,這將創建用戶並定義用戶的全名,名字,姓氏,用戶名,SAM名稱,電子郵件,標題,描述和管理員。它也會設置密碼。使用CSV在AD中創建批量用戶

我很想談談下面的腳本如何看起來。如果您有任何問題或需要任何其他信息,請告訴我。

Import-Module activedirectory 

$ADUsers = Import-CSV C:\scripts\hourlyimport.csv 

foreach ($User in $ADUsers) 
{ 
    #read user data from each field in each row and assign the data to a variable as below 

    $Username = $User.username 
    $Firstname = $User.firstname 
    $Lastname = $User.lastname 
    $Password = $User.password 
    $OU   = $User.ou 
    $Title  = $User.title 
    $Manager = $User.manager 

    #check to see if the user already exists in AD 

    if (Get-ADUser -F {SamAccountName -eq $Username}) 
    { 
     #if user does exist, give a warning 

     Write-Warning "A user account with username $Username already exist in Active Directory. Say wha?!?" 
    } 
    else 
    { 
     #if user does not exist then proceed to create the new user account 

     #account will be created in the OU provided by the $OU variable read from the CSV file 

     New-ADUser ` 
      -SamAccountName $Username ` 
      -UserPrincipalName "[email protected]" ` 
     -Email "[email protected]" ` 
      -Name "$Firstname $Lastname" ` 
      -GivenName $Firstname ` 
      -Surname $Lastname ` 
      -Enabled $True ` 
      -DisplayName "$Lastname, $Firstname" ` 
      -Path $OU ` 
     -Description "$Title" ` 
     -Title "$Title" ` 
     -Manager "$Manager" ` 
      -AccountPassword (convertto-securestring $Password -AsPlainText -Force) 
    } 
} 

回答

1

對我來說看起來不錯。你有點不符合"的使用,例如你不需要寫-Title "$Title",在這種情況下你可以不用"

你可以在這裏做splatting的一些奇特的優化,減少了作業,但是由於它在很多讀者中是一個未知的特性,所以我不會在這裏找它。

我缺少的一件事是錯誤處理。使用默認設置時,腳本會在出錯時打印出錯誤,但繼續循環。這是打算?通常在腳本開始時通過設置$ErrorActionPreference來明確表達您的意圖是一種很好的做法。

+0

明白了。所以在組合數據時我只需要引用,比如添加@ domain.com或創建一個「完整」名稱? –

+0

是的,在變量中使用'''是使用'string.Format'的PowerShell方法 – TToni

相關問題