2016-08-12 212 views
0

我需要調整此腳本以從CSV創建一批本地用戶,但跳過已經創建的帳戶。我可以建立得很好,但如何我省略已經存在從csv創建本地帳戶,但如何省略已創建的帳戶?

$computer = $Env:ComputerName 
$text = "C:\accounts.csv" 
$user = import-csv -path $text 
    foreach($strUser) in $user) 
{ 
$user = $struser.user 
$password = $struser.password 
$description = $struser.description 
$group = $struser.group 
Clear-Host 
$ObjOU = [ADSI]"WinNT://$computer" 
$objUser = $objOU.Create("User", $user) 
$objUser.setpassword($password) 
$objUser.put("description",$description) 
$objUser.SetInfo() 
$objGroup = [ADSI]"WinNT://$computer/$group" 
$objGroup.add("WinNT://$computer/$user") 
$objGroup.SetInfo() 
} 
+0

它失敗,原因是您必須提供有關的右手側的值表達式「 - 」操作。 在C:\ Windows \ TEMP \ AltirisScript0B427C10272370E8748.ps1:12 char:12 + If($ user - <<<< notin($ ObjOU.Children | Where {{_。SchemaClassName -eq'user'} )) + CategoryInfo:ParserError:(:) [],ParseException + FullyQualifiedErrorId:ExpectedValueExpression – CrumBum

+0

我會爲此使用什麼表達式? – CrumBum

回答

0
#setting Variables 
$computer = $Env:ComputerName 
$text = "C:\ProgramData\Bridge Operators.csv" 
$user = import-csv -path $text 
foreach($strUser in $user) 
{ 
$user = $struser.user 
$password = $struser.password 
$description = $struser.description 
$group = $struser.group 
Clear-Host 
##First check if user exists 
$objComputer = [ADSI]"WinNT://$computer,computer" 
$colUsers = ($objComputer.psbase.children | Where-Object {$_.psBase.schemaClassName -eq "User"} | Select-Object -expand Name) 
$userFound = $colUsers -contains $user 
if (! $userFound) { 
    write-host "The $user account did not exist." 
    write-host "Creating $user" 
$ObjOU = [ADSI]"WinNT://$computer" 
$objUser = $objOU.Create("User", $user) 
$objUser.setpassword($password) 
$objUser.put("description",$description) 
$objUser.SetInfo() 
$objGroup = [ADSI]"WinNT://$computer/$group" 
$objGroup.add("WinNT://$computer/$user") 
$objGroup.SetInfo() 
} 
else { 
    write-host "$user account exists." 
    write-host "skipping" 
}} 
0

本地帳戶,您可以得到的信息,你已經拉動本地用戶帳戶的列表。然後在創建用戶之前僅對其進行過濾。

$computer = $Env:ComputerName 
$text = "C:\accounts.csv" 
$user = import-csv -path $text 
$ObjOU = [ADSI]"WinNT://$computer" 
    foreach($strUser in $user) 
{ 
$user = $struser.user 
$password = $struser.password 
$description = $struser.description 
$group = $struser.group 
Clear-Host 
If($user -notin ($ObjOU.Children|Where{$_.SchemaClassName -eq 'user'}).Name){ 
    $objUser = $objOU.Create("User", $user) 
    $objUser.setpassword($password) 
    $objUser.put("description",$description) 
    $objUser.SetInfo() 
} 
$objGroup = [ADSI]"WinNT://$computer/$group" 
$objGroup.add("WinNT://$computer/$user") 
$objGroup.SetInfo() 
} 
+0

我很感激幫助 - 所以它不喜歡IF聲明,也不會創建賬戶。它希望在' - '運算符的右側有一個值表達式。 11 char 12. – CrumBum

+0

FIXED!它現在創建該帳戶,如果未找到並跳過任何已創建的帳戶。 – CrumBum