我想为我新创建的Active Directory用户添加随机生成的密码

时间:2013-06-19 16:59:01

标签: powershell powershell-v2.0 powershell-v3.0 powershell-ise

我想在我新创建的Active Directory用户中添加一个随机生成的密码。我写了一个生成密码的函数。我正在使用Powershell V2.0

我尝试了以下但没有帮助。

Import-Module ActiveDirectory
[xml]$dataSource = Get-Content C:\Names1.xml

$name = Read-Host 'Please enter the table name : '

$user_logon = $dataSource.names.$name | ? { $_.Rule_Label -eq 'Regular service account (user logon)'}

$display_name = $dataSource.names.$name | ? { $_.Rule_Label -eq 'Regular service account (display name)'}

$pre_windows = $dataSource.names.$name | ? { $_.Rule_Label -eq 'Regular service account (pre-Windows 2000)'}

Function GET-Temppassword() { 
Param(
[int]$length=10, 
[string[]]$sourcedata 
)

For ($loop=1; $loop –le $length; $loop++) { 
    $TempPassword+=($sourcedata | GET-RANDOM)
    }

return $TempPassword
}


switch ($name) 
{ 
    DevTable{foreach($dataRecord in $dataSource) 
    {
    try     
    {
    $cn=$user_logon.Output_Value
    $sAMAccountName=$user_logon.Output_Value
    $givenName=$user_logon.Output_Value
    $sn=$user_logon.Output_Value 
    $displayName=$display_name.Output_Value 
    $userPrincipalName=$sAMAccountName + “@test.com”;

    $alphabet=$NULL;For ($a=65;$a –le 90;$a++) {$alphabet+=,[char][byte]$a }
    $TempPassword1 = GET-Temppassword –length 10 –sourcedata $alphabet


    New-ADUser $cn -SamAccountName $sAMAccountName -GivenName $givenName -Surname $sn -DisplayName $displayName -UserPrincipalName $userPrincipalName -AccountPassword $TempPassword1 -PasswordNeverExpires $true -Path "OU=Service,OU=Accounts,DC=xyz,DC=com"     

    set-aduser $cn -replace @{comment="xxyyzz"}
    set-aduser $cn -replace @{"account"=1}      

    Add-ADGroupMember -Identity xyz -Member $cn
    Add-ADGroupMember -Identity "Service Accounts" -Member $cn

    write-host "New DevTable ADUser has been created!!!";
    }

    catch [Exception]
    {

        write-host "Error - Requested AD Service Account is already present...Please check & confirm " -foreground "red"
    }
    }   
    break;
    }

    default {"The table could not be determined!!!"}    

}   

[System.GC]::Collect()

请看一下。谢谢。

1 个答案:

答案 0 :(得分:0)

这是为了使$ sourceData可以是如下字符串。如果你真的想传递$ sourcedata作为char数组,从函数中删除[char []]强制转换。

$sourcedata="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-$"

Function GET-Temppassword() { 
  Param(
  [int]$length=10, 
  [string[]]$sourcedata 
  )

  -join ([char[]] $sourcedata | GET-RANDOM -count $length)
}

get-temppassword $sourceData 20
GVTXxF13ibnBK5AQOu-P
相关问题