iancua
iancua

Reputation: 29

Create user with "password never expires" in PowerShell

I want to create a lot of users in my AD with a CSV file and a PowerShell script, but I don't find how to create a user with the argument "PasswordNeverExpire" and "user is active/inactive".

My CSV:

enter image description here

Upvotes: 2

Views: 17869

Answers (3)

BabaJohnson
BabaJohnson

Reputation: 11

A simple solution which has worked for me is this way:

$password = ConvertTo-SecureString "passwd123" –AsPlainText –Force
$user = "userxyz"
New-ADUser -Name $user -AccountPassword $password
Set-ADUser $user -PasswordNeverExpires $true

Upvotes: 1

AdminOfThings
AdminOfThings

Reputation: 25011

You can process each row in the CSV (myCSV.csv in this example) as an object in PowerShell. During that process, you can manipulate each column (a property) value to fit your command. You can use Splatting to make things more readable and manageable.

Import-Csv MyCSV.csv | Foreach-Object {
    $Params = @{
        GivenName = $_.firstname
        Surname = $_.lastname
        SamAccountName = $_.username
        AccountPassword = $_.password | ConvertTo-SecureString -AsPlainText -Force
        Enabled = [bool]$_.enable
        PasswordNeverExpires = [bool]$_.PasswordNeverExpires
        Name = "{0} {1}" -f $_.firstname,$_.lastname
        Path = $_.ou
    }
    if ([bool]$_.AccountNeverExpires -eq $False) {
        $Params.Add(AccountExpirationDate,(Get-Date -Year 2020 -Month 1 -Day 1))
    }
    New-ADUser @Params
}

Considerations:

  • You may want to finely control UserPrincipalName. If so, you can simply add it to the $Params hash table with your preferred format.
  • -Name is a required parameter. So I've added it to the hash table. I used the format operator (-f) to format the string. You can format it as desired.
  • You have AccountNeverExpires set to False for a number of your entries. This means you will need to pass the parameter -AccountExpirationDate a valid [datetime] object. I used January 1, 2020 in the example. Please update this to something appropriate.
  • The *-ADUser commands that support a password parameter expect secure strings. This means you will need to convert plain text passwords before passing them to those parameters.
  • True and False values read from a CSV file are read as strings. The *-ADUser commands expect those values to be Boolean type. In those cases, I used the [bool] type accelerator to cast those values to Boolean.

Upvotes: 0

Matthew
Matthew

Reputation: 1450

You could create the account and use the following

Set-ADUser -Identity <name> -PasswordNeverExpires $true

this will set the account's password to never expire, if you're using a loop to create the account you can add that into it.

Upvotes: 4

Related Questions