PasswordNeverExpires vs MsolPasswordPolicy

Can anyone explain the difference between setting this:
Set-MsolUserPassword -UserPrincipalName [email protected] -PasswordNeverExpires
and:
Set-MsolPasswordPolicy -DomainName  -NotificationDays  –ValidityPeriod
If the user password is set to never expire, does it still expire every 90 days anyway?
How can you set it to never expire?

If you want to set it to never expire do
Set-MsolUser -UserPrincipalName [email protected] -PasswordNeverExpires $true
If you want to do it for all users do
Get-MsolUser | Set-MsolUser -PasswordNever Expires
Set-MsolUserPassword sets a user password
Set-MsolPasswordPolicy sets password policy for the domain, validity between 14 to 730 days. However if a user is set to password never expires, it won't expire.
onlinehelp.microsoft.com/en-us/office365-enterprises/ff637619.aspx

Similar Messages

  • PowerShell don't give out Information about -PasswordNeverExpire

    Hello,in tested a command for PowerShell on my VMware Windows Server 2012 R2. Its an AD and i want to find the Accounts having the Settings on password never expire on True.This is my command:Search-ADAccount -PasswordNeverExpires | sort-object Name | select-object Name, PasswordNeverExpiresI created Some testaccounts but it only shows me this:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------PS AD:\> Search-ADAccount -passwordneverexpires | sort-object name | select-object Name, passwordneverexpires
    Name                                                                                                                                                                       passwordneverexpires
    Admin                                                                                                                                                                                      True
    Administrator                                                                                                                                                                              True
    Gast                                                                                                                                                                                       True
    PS AD:\> -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------With anouther command i see that my Users are existing:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------PS AD:\> get-aduser -filter * -properties passwordneverexpires |ft Name, Passwordneverexpires
    Name                                                                                                                                                                       Passwordneverexpires
    Administrator                                                                                                                                                                              True
    Gast                                                                                                                                                                                       True
    Admin                                                                                                                                                                                      True                                                                                                                                                                             
    Test 1                                                                                                                                                                                         
    Test 2                                                                                                                                                                                         
    Test 3                                                                                                                                                                                         
    Test 4                                                                                                                                                                                         
    Test 5                                                                                                                                                                                         
    Test 6                                                                                                                                                                                         
    Test 7                                                                                                                                                                                         
    PS AD:\> -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------I searched in the Internet for a while but I didn't get anything about this, maybe i missed something?Thanks, Alex

    Hello,
    see similar question the Windows Powershell forum:
    http://social.technet.microsoft.com/Forums/Lync/en-US/0f6cd489-0a8f-41d0-bed2-104af82600c6/powershell-script-to-output-all-users-who-have-no-password-expiry?forum=winserverpowershell
    Best regards
    Meinolf Weber
    MVP, MCP, MCTS
    Microsoft MVP - Directory Services
    My Blog: http://blogs.msmvps.com/MWeber
    Disclaimer: This posting is provided AS IS with no warranties or guarantees and confers no rights.
    Twitter:  

  • Office365 - PasswordNeverExpires status doesn't show any status

    Dear all,
    I have a question about office365 passwordneverexpire setting.
    Normally, when I execute the command "get-msoluser -userprincipalname "UserID" |select PasswordNeverExpires ", I can see the status "True/False". But, in my case, it doesn't show any status.
    Thanks,
    Min

    Looks like the "Administrative queues" implementation could have been planned around design time. Then the requests could be assigned and managed by different roles(groups) member with different access levels in OIM.
    However, in my current setup - all workflows follows this rule 1) Route the request for manager approval 2) After successful manager approval, route it for application group approval (2nd step of approval). Implementation of "Administrative queues" in this setup looks difficult to me.
    Any comment?
    Thanks,

  • ADUser PasswordNeverExpires -eq 'false'

    I am trying to get a list of user accounts that have PasswordNeverExpires -eq 'false' or true.
    I can run a this:
    get-aduser -filter * -properties passwordneverexpires | Select-Object PasswordNeverExpires
    and i get a list of all true and false.
    why when i am running this line:
    get-aduser -filter * | where {$_.PasswordNeverExpires -eq 'false'}
    i get nothing?
    Thank you.

    Properties is spelled wrong.
    My script skips the filter because SamAccountName is an Identity YOu do not need to filter.
    Get-ADUser $_ -Properties PasswordExpired,PasswordNeverExpires     
    You should not place fileter selectors and formatters inside of the loop.
    Get-Content C:\Source\Scripts\ListOfAccounts.txt |
        ForEach-Object{
            Get-ADUser $_ -Properties PasswordExpired,PasswordNeverExpires     
    Now place the selectors and formatters at teh end of thepipeline.
    Get-Content C:\Source\Scripts\ListOfAccounts.txt |
        ForEach-Object{
            Get-ADUser $_ -Properties PasswordExpired,PasswordNeverExpires     
        } |
        Select-Object -Property samaccountname,enabled,PasswordExpired,PasswordNeverExpires
    This is more efficient and easier to manage
    ¯\_(ツ)_/¯

  • Need Help on powershell Script to send mails in different languages

    Hello, Just wanted to use the script below to remind users of password expiry date (I got it from internet New-Passwordreminder.ps1). We have companies in many countries, so the email should be in the language of that country. So since our users are in different
    OU's according to countries, I thought some one could help me edit this script and say if the user is in AB ou then email in english will be sent, if in BC ou then the email will be in Russian....So in the script I will have all the languages I need
    to have written.
    <#
    .SYNOPSIS
      Notifies users that their password is about to expire.
    .DESCRIPTION
        Let's users know their password will soon expire. Details the steps needed to change their password, and advises on what the password policy requires. Accounts for both standard Default Domain Policy based password policy and the fine grain
    password policy available in 2008 domains.
    .NOTES
        Version            : v2.6 - See changelog at
    http://www.ehloworld.com/596
        Wish list      : Better detection of Exchange server
                  : Set $DaysToWarn automatically based on Default Domain GPO setting
                  : Description for scheduled task
                  : Verify it's running on R2, as apparently only R2 has the AD commands?
                  : Determine password policy settings for FGPP users
                  : better logging
        Rights Required   : local admin on server it's running on
        Sched Task Req'd  : Yes - install mode will automatically create scheduled task
        Lync Version    : N/A
        Exchange Version  : 2007 or later
        Author           : M. Ali (original AD query), Pat Richard, Exchange MVP
        Email/Blog/Twitter :
    [email protected]  http://www.ehloworld.com @patrichard
        Dedicated Post   :
    http://www.ehloworld.com/318
        Disclaimer       : You running this script means you won't blame me if this breaks your stuff.
        Info Stolen from   : (original)
    http://blogs.msdn.com/b/adpowershell/archive/2010/02/26/find-out-when-your-password-expires.aspx
                  : (date)
    http://technet.microsoft.com/en-us/library/ff730960.aspx
                : (calculating time)
    http://blogs.msdn.com/b/powershell/archive/2007/02/24/time-till-we-land.aspx
    http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/23fc5ffb-7cff-4c09-bf3e-2f94e2061f29/
    http://blogs.msdn.com/b/adpowershell/archive/2010/02/26/find-out-when-your-password-expires.aspx
                : (password decryption)
    http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/f90bed75-475e-4f5f-94eb-60197efda6c6/
                : (determine per user fine grained password settings)
    http://technet.microsoft.com/en-us/library/ee617255.aspx
    .LINK    
        http://www.ehloworld.com/318
    .INPUTS
      None. You cannot pipe objects to this script
    .PARAMETER Demo
      Runs the script in demo mode. No emails are sent to the user(s), and onscreen output includes those who are expiring soon.
    .PARAMETER Preview
      Sends a sample email to the user specified. Usefull for testing how the reminder email looks.
    .PARAMETER PreviewUser
      User name of user to send the preview email message to.
    .PARAMETER Install
      Create the scheduled task to run the script daily. It does NOT create the required Exchange receive connector.
    .EXAMPLE
      .\New-PasswordReminder.ps1
      Description
      Searches Active Directory for users who have passwords expiring soon, and emails them a reminder with instructions on how to change their password.
    .EXAMPLE
      .\New-PasswordReminder.ps1 -demo
      Description
      Searches Active Directory for users who have passwords expiring soon, and lists those users on the screen, along with days till expiration and policy setting
    .EXAMPLE
      .\New-PasswordReminder.ps1 -Preview -PreviewUser [username]
      Description
      Sends the HTML formatted email of the user specified via -PreviewUser. This is used to see what the HTML email will look like to the users.
    .EXAMPLE
      .\New-PasswordReminder.ps1 -install
      Description
      Creates the scheduled task for the script to run everyday at 6am. It will prompt for the password for the currently logged on user. It does NOT create the required Exchange receive connector.
    #>
    #Requires -Version 2.0
    [cmdletBinding(SupportsShouldProcess = $true)]
    param(
     [parameter(ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true, Mandatory = $false)]
     [switch]$Demo,
     [parameter(ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true, Mandatory = $false)]
     [switch]$Preview,
     [parameter(ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true, Mandatory = $false)]
     [switch]$Install,
     [parameter(ValueFromPipeline = $false, ValueFromPipelineByPropertyName = $true, Mandatory = $false)]
     [string]$PreviewUser
    Write-Verbose "Setting variables"
    [string]$Company = "Contoso Ltd"
    [string]$OwaUrl = "https://mail.contoso.com"
    [string]$PSEmailServer = "10.9.0.11"
    [string]$EmailFrom = "Help Desk <[email protected]>"
    [string]$HelpDeskPhone = "(586) 555-1010"
    [string]$HelpDeskURL = "https://intranet.contoso.com/"
    [string]$TranscriptFilename = $MyInvocation.MyCommand.Name + " " + $env:ComputerName + " {0:yyyy-MM-dd hh-mmtt}.log" -f (Get-Date)
    [int]$global:UsersNotified = 0
    [int]$DaysToWarn = 14
    [string]$ImagePath = "http://www.contoso.com/images/new-passwordreminder.ps1"
    [string]$ScriptName = $MyInvocation.MyCommand.Name
    [string]$ScriptPathAndName = $MyInvocation.MyCommand.Definition
    [string]$ou
    [string]$DateFormat = "d"
    if ($PreviewUser){
     $Preview = $true
    Write-Verbose "Defining functions"
    function Set-ModuleStatus {
     [cmdletBinding(SupportsShouldProcess = $true)]
     param (
      [parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $true, HelpMessage = "No module name specified!")]
      [string]$name
     if(!(Get-Module -name "$name")) {
      if(Get-Module -ListAvailable | ? {$_.name -eq "$name"}) {
       Import-Module -Name "$name"
       # module was imported
       return $true
      } else {
       # module was not available (Windows feature isn't installed)
       return $false
     }else {
      # module was already imported
      return $true
    } # end function Set-ModuleStatus
    function Remove-ScriptVariables { 
     [cmdletBinding(SupportsShouldProcess = $true)]
     param($path)
     $result = Get-Content $path | 
     ForEach { if ( $_ -match '(\$.*?)\s*=') {     
       $matches[1]  | ? { $_ -notlike '*.*' -and $_ -notmatch 'result' -and $_ -notmatch 'env:'} 
     ForEach ($v in ($result | Sort-Object | Get-Unique)){  
      Remove-Variable ($v.replace("$","")) -ErrorAction SilentlyContinue
    } # end function Get-ScriptVariables
    function Install {
     [cmdletBinding(SupportsShouldProcess = $true)]
     param()
    http://technet.microsoft.com/en-us/library/cc725744(WS.10).aspx
     $error.clear()
     Write-Host "Creating scheduled task `"$ScriptName`"..."
     $TaskPassword = Read-Host "Please enter the password for $env:UserDomain\$env:UserName" -AsSecureString
     $TaskPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($TaskPassword))
     # need to fix the issue with spaces in the path
     schtasks /create /tn $ScriptName /tr "$env:windir\system32\windowspowershell\v1.0\powershell.exe -psconsolefile '$env:ExchangeInstallPath\Bin\exshell.psc1' -command $ScriptPathAndName" /sc Daily /st 06:00 /ru $env:UserDomain\$env:UserName /rp
    $TaskPassword | Out-Null
     if (!($error)){
      Write-Host "done!" -ForegroundColor green
     }else{
      Write-Host "failed!" -ForegroundColor red
     exit
    } # end function Install
    function Get-ADUserPasswordExpirationDate {
     [cmdletBinding(SupportsShouldProcess = $true)]
     Param (
      [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline = $true, HelpMessage = "Identity of the Account")]
      [Object]$accountIdentity
     PROCESS {
      Write-Verbose "Getting the user info for $accountIdentity"
      $accountObj = Get-ADUser $accountIdentity -properties PasswordExpired, PasswordNeverExpires, PasswordLastSet, name, mail
      # Make sure the password is not expired, and the account is not set to never expire
        Write-Verbose "verifying that the password is not expired, and the user is not set to PasswordNeverExpires"
        if (((!($accountObj.PasswordExpired)) -and (!($accountObj.PasswordNeverExpires))) -or ($PreviewUser)) {
         Write-Verbose "Verifying if the date the password was last set is available"
         $passwordSetDate = $accountObj.PasswordLastSet      
          if ($passwordSetDate -ne $null) {
           $maxPasswordAgeTimeSpan = $null
            # see if we're at Windows2008 domain functional level, which supports granular password policies
            Write-Verbose "Determining domain functional level"
            if ($global:dfl -ge 4) { # 2008 Domain functional level
              $accountFGPP = Get-ADUserResultantPasswordPolicy $accountObj
              if ($accountFGPP -ne $null) {
               $maxPasswordAgeTimeSpan = $accountFGPP.MaxPasswordAge
         } else {
          $maxPasswordAgeTimeSpan = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
        } else { # 2003 or ealier Domain Functional Level
         $maxPasswordAgeTimeSpan = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge
        if ($maxPasswordAgeTimeSpan -eq $null -or $maxPasswordAgeTimeSpan.TotalMilliseconds -ne 0) {
         $DaysTillExpire = [math]::round(((New-TimeSpan -Start (Get-Date) -End ($passwordSetDate + $maxPasswordAgeTimeSpan)).TotalDays),0)
         if ($preview){$DaysTillExpire = 1}
         if ($DaysTillExpire -le $DaysToWarn){
          Write-Verbose "User should receive email"
          $PolicyDays = [math]::round((($maxPasswordAgeTimeSpan).TotalDays),0)
          if ($demo) {Write-Host ("{0,-25}{1,-8}{2,-12}" -f $accountObj.Name, $DaysTillExpire, $PolicyDays)}
                # start assembling email to user here
          $EmailName = $accountObj.Name      
          $DateofExpiration = (Get-Date).AddDays($DaysTillExpire)
          $DateofExpiration = (Get-Date($DateofExpiration) -f $DateFormat)      
    Write-Verbose "Assembling email message"      
    [string]$emailbody = @"
    <html>
     <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
     </head>
    <body>
     <table id="email" border="0" cellspacing="0" cellpadding="0" width="655" align="center">
      <tr>
       <td align="left" valign="top"><img src="$ImagePath/spacer.gif" alt="Description: $ImagePath/spacer.gif" width="46" height="28" align="absMiddle">
    if ($HelpDeskURL){     
    $emailbody += @" 
       <font style="font-size: 10px; color: #000000; line-height: 16px; font-family: Verdana, Arial, Helvetica, sans-serif">If this e-mail does not appear properly, please <a href="$HelpDeskURL" style="font-weight:
    bold; font-size: 10px; color: #cc0000; font-family: verdana, arial, helvetica, sans-serif; text-decoration: underline">click here</a>.</font>
    $emailbody += @"   
       </td>
      </tr>
      <tr>
    if ($HelpDeskURL){  
    $emailbody += @"
       <td height="121" align="left" valign="bottom"><a href="$HelpDeskURL"><img src="$ImagePath/header.gif" border="0" alt="Description: $ImagePath/header.gif"
    width="655" height="121"></a></td>
    }else{
    $emailbody += @" 
       <td height="121" align="left" valign="bottom"><img src="$ImagePath/header.gif" border="0" alt="Description: $ImagePath/header.gif" width="655" height="121"></td>
    $emailbody += @"
      </tr>
      <tr>
       <td>
        <table id="body" border="0" cellspacing="0" cellpadding="0">
         <tr>
          <td width="1" align="left" valign="top" bgcolor="#a8a9ad"><img src="$ImagePath/spacer50.gif" alt="Description: $ImagePath/spacer50.gif" width="1"
    height="50"></td>
          <td><img src="$ImagePath/spacer.gif" alt="Description: $ImagePath/spacer.gif" width="46" height="106"></td>
          <td id="text" width="572" align="left" valign="top" style="font-size: 12px; color: #000000; line-height: 17px; font-family: Verdana, Arial, Helvetica, sans-serif">
    if ($DaysTillExpire -le 1){
     $emailbody += @"
      <div align='center'>
       <table border='0' cellspacing='0' cellpadding='0' style='width:510px; background-color: white; border: 0px;'>
        <tr>
         <td align='right'><img width='36' height='28' src='$ImagePath/image001b.gif' alt='Description: $ImagePath/image001b.gif'></td> 
         <td style="font-family: verdana; background: #E12C10; text-align: center; padding: 0px; font-size: 9.0pt; color: white">ALERT: You must change your password today or you will be locked out!</td>  
         <td align='left'><img border='0' width='14' height='28' src='$ImagePath/image005b.gif' alt='Description: $ImagePath/image005b.gif'></td>
        </tr>
       </table>
      </div>
    $emailbody += @"
       <p style="font-weight: bold">Hello, $EmailName,</p>
       <p>It's change time again! Your $company password expires in <span style="background-color: red; color: white; font-weight: bold;">&nbsp;$DaysTillExpire&nbsp;</span> day(s), on $DateofExpiration.</p>
       <p>Please use one of the methods below to update your password:</p>
       <ol>
        <li>$company office computers and Terminal Server users: You may update your password on your computer by pressing Ctrl-Alt-Delete and selecting 'Change Password' from the available options. If you use a $company laptop in addition
    to a desktop PC, be sure and read #3 below.</li>
        <li>Remote Outlook Client, Mac, and/or Outlook Web App users: If you only access our email system, please use the following method to easily change your password:</li>
        <ul>
         <li>Log into <a href="$owaurl">Outlook Web App</a> using Internet Explorer (PC) or Safari or Firefox (Mac).</li>
         <li>Click on the Options button in the upper right corner of the page.</li>  
         <li>Select the &quot;Change Password&quot; link to change your password.</li>
         <li>Enter your current password, then your new password twice, and click Save</li>
         <li><span style="font-weight: bold">NOTE:</span> You will now need to use your new password when logging into Outlook Web App, Outlook 2010, SharePoint, Windows Mobile (ActiveSync) devices, etc. Blackberry
    Enterprise Users (BES) will not need to update their password. Blackberry Internet Service (BIS) users will be required to use their new password on their device.</li>
        </ul>
        <li>$company issued laptops: If you have been issued a $company laptop, you must be in a corporate office and directly connected to the company network to change your password. If you also use a desktop PC in the office, you must
    remember to always update your domain password on the laptop first. Your desktop will automatically use the new password.</li>
        <ul>
         <li>Log in on laptop</li>
         <li>Press Ctrl-Alt-Delete and select 'Change Password' from the available options.</li>
         <li>Make sure your workstation (if you have one) has been logged off any previous sessions so as to not cause conflict with your new password.</li>
        </ul>
       </ol>
       <p>Think you've got a complex password? Run it through the <a href="The">http://www.passwordmeter.com/">The Password Meter</a></p>
       <p>Think your password couldn't easily be hacked? See how long it would take: <a href="How">http://howsecureismypassword.net/">How Secure Is My Password</a></p>
       <p>Remember, if you do not change your password before it expires on $DateofExpiration, you will be locked out of all $company Computer Systems until an Administrator unlocks your account.</p>
       <p>If you are traveling or will not be able to bring your laptop into the office before your password expires, please call the number below for additional instructions.</p>
       <p>You will continue to receive these emails daily until the password is changed or expires.</p>
       <p>Thank you,<br />
       The $company Help Desk<br />
       $HelpDeskPhone</p>
    if ($accountFGPP -eq $null){
     $emailbody += @"
       <table style="background-color: #dedede; border: 1px solid black">
        <tr>
         <td style="font-size: 12px; color: #000000; line-height: 17px; font-family: Verdana, Arial, Helvetica, sans-serif"><b>$company Password Policy</b>
          <ul>
           <li>Your password must have a minimum of a $MinPasswordLength characters.</li>
           <li>You may not use a previous password.</li>
           <li>Your password must not contain parts of your first, last, or logon name.</li>
           <li>Your password must be changed every $PolicyDays days.</li>
    if ($PasswordComplexity){
     Write-Verbose "Password complexity"
     $emailbody += @"
           <li>Your password requires a minimum of two of the following three categories:</li>
           <ul>
            <li>1 upper case character (A-Z)</li>
            <li>1 lower case character (a-z)</li>
            <li>1 numeric character (0-9)</li>        
           </ul>
    $emailbody += @"
           <li>You may not reuse any of your last $PasswordHistory passwords</li>
          </ul>
         </td>
        </tr>
       </table>
    $emailbody += @"        
           </td>
           <td width="49" align="left" valign="top"><img src="$ImagePath/spacer50.gif" alt="" width="49" height="50"></td>
           <td width="1" align="left" valign="top" bgcolor="#a8a9ad"><img src="$ImagePath/spacer50.gif" alt="Description: $ImagePath/spacer50.gif" width="1"
    height="50"></td>
          </tr>
         </table>
         <table id="footer" border="0" cellspacing="0" cellpadding="0" width="655">
          <tr>
           <td><img src="$ImagePath/footer.gif" alt="Description: $ImagePath/footer.gif" width="655" height="81"></td>
          </tr>
         </table>
         <table border="0" cellspacing="0" cellpadding="0" width="655" align="center">
          <tr>
           <td align="left" valign="top"><img src="$ImagePath/spacer.gif" alt="Description: $ImagePath/spacer.gif" width="36" height="1"></td>
           <td align="middle" valign="top"><font face="Verdana" size="1" color="#000000"><p>This email was sent by an automated process.
    if ($HelpDeskURL){
    $emailbody += @"               
           If you would like to comment on it, please visit <a href="$HelpDeskURL"><font color="#ff0000"><u>click here</u></font></a>
    $emailbody += @"               
            </p><p style="color: #009900;"><font face="Webdings" size="4">P</font> Please consider the environment before printing this email.</p></font>
           </td>
           <td align="left" valign="top"><img src="$ImagePath/spacer.gif" alt="Description: $ImagePath/spacer.gif" width="36" height="1"></td>
          </tr>
         </table>
        </td>
       </tr>
      </table>
     </body>
    </html>
          if (!($demo)){
           $emailto = $accountObj.mail
           if ($emailto){
            Write-Verbose "Sending demo message to $emailto"
            Send-MailMessage -To $emailto -Subject "Your password expires in $DaysTillExpire day(s)" -Body $emailbody -From $EmailFrom -Priority High -BodyAsHtml
            $global:UsersNotified++
           }else{
            Write-Verbose "Can not email this user. Email address is blank"
    } # end function Get-ADUserPasswordExpirationDate
    if ($install){
     Write-Verbose "Install mode"
     Install
    Write-Verbose "Checking for ActiveDirectory module"
    if ((Set-ModuleStatus ActiveDirectory) -eq $false){
     $error.clear()
     Write-Host "Installing the Active Directory module..." -ForegroundColor yellow
     Set-ModuleStatus ServerManager
     Add-WindowsFeature RSAT-AD-PowerShell
     if ($error){
      Write-Host "Active Directory module could not be installed. Exiting..." -ForegroundColor red;
      if ($transcript){Stop-Transcript}
      exit
    Write-Verbose "Getting Domain functional level"
    $global:dfl = (Get-AdDomain).DomainMode
    # Get-ADUser -filter * -properties PasswordLastSet,EmailAddress,GivenName -SearchBase "OU=Users,DC=domain,DC=test" |foreach {
    if (!($PreviewUser)){
     if ($ou){
      Write-Verbose "Filtering users to $ou"
      $users = Get-AdUser -filter * -SearchScope subtree -SearchBase $ou -ResultSetSize $null
     }else{
      $users = Get-AdUser -filter * -ResultSetSize $null
    }else{
     Write-Verbose "Preview mode"
     $users = Get-AdUser $PreviewUser
    if ($demo){
     Write-Verbose "Demo mode"
     # $WhatIfPreference = $true
     Write-Host "`n"
     Write-Host ("{0,-25}{1,-8}{2,-12}" -f "User", "Expires", "Policy") -ForegroundColor cyan
     Write-Host ("{0,-25}{1,-8}{2,-12}" -f "========================", "=======", "===========") -ForegroundColor cyan
    Write-Verbose "Setting event log configuration"
    $evt = new-object System.Diagnostics.EventLog("Application")
    $evt.Source = $ScriptName
    $infoevent = [System.Diagnostics.EventLogEntryType]::Information
    $EventLogText = "Beginning processing"
    $evt.WriteEntry($EventLogText,$infoevent,70)
    Write-Verbose "Getting password policy configuration"
    $DefaultDomainPasswordPolicy = Get-ADDefaultDomainPasswordPolicy
    [int]$MinPasswordLength = $DefaultDomainPasswordPolicy.MinPasswordLength
    # this needs to look for FGPP, and then default to this if it doesn't exist
    [bool]$PasswordComplexity = $DefaultDomainPasswordPolicy.ComplexityEnabled
    [int]$PasswordHistory = $DefaultDomainPasswordPolicy.PasswordHistoryCount
    ForEach ($user in $users){
     Get-ADUserPasswordExpirationDate $user.samaccountname
    Write-Verbose "Writing summary event log entry"
    $EventLogText = "Finished processing $global:UsersNotified account(s). `n`nFor more information about this script, run Get-Help .\$ScriptName. See the blog post at
    http://www.ehloworld.com/318."
    $evt.WriteEntry($EventLogText,$infoevent,70)
    # $WhatIfPreference = $false
    # Remove-ScriptVariables -path $MyInvocation.MyCommand.Name
    Remove-ScriptVariables -path $ScriptPathAndName

    Hi petro_jemes,
    Just a little claritification, you need to add the value to the variable "[string]$ou", and also change the language in the variable "$emailbody" in the function "Get-ADUserPasswordExpirationDate".
    I hope this helps.

  • Can't find my mistake

    I am writing a user creation script and just working through my variables at this point.  So i have the script importing a csv file with user info.  Based on that user info it creates a series of variables three of which i am using the switch command
    to choose the string that is associated with another string.  that all seems to work fine however when the message to type the $dept variable.  the read-host is showing the $upn of the first user to go through not the user that it is actually setting
    the variable for.  like i said the variables seem to be setting properly just the output in the shell shows the wrong upn for what i am updating.. code and output below:         
    function TFX-CreateNewUsers{
           [CmdletBinding()]
            param(
                [string]$logfile = 'c:\PowerShell_Logs\UserCreationErrors.txt',
                [Switch]$LogErrors,
                [Parameter(Mandatory = $true,
                           valuefrompipeline = $true,
                           HelpMessage = "Please provide valid path and file name to the CSV file with the user information.")]
                [Alias('csv')]
                [string]$FilePath
            $date = Get-Date -Format g
            $addn = (Get-ADDomain).DistinguishedName
            $dnsroot = (Get-ADDomain).DNSRoot
            $userlist = Import-Csv $FilePath
            $userlist | ForEach-Object{
                  If (($_.GivenName -eq '') -Or ($_.LastName -eq ''))
                       {Write-Host 'ERROR: Please provide valid GivenName, LastName and Initials. Processing stopped' -ForegroundColor Red
                       "$date ERROR: Please provide valid GivenName, LastName and Initials. Processing stopped" | Out-File $logfile -Append
                       Break
                  Else {
                       $upn="[email protected]"
                       $site=$_.site
                          switch ($site) {
                              Arl {$homed = "\\share\global\home\medical\na\arl"}
                              Ash {$homed ="\\share2\user"}
                          switch ($site) {
                              Arl {$HDrive = "H:"}
                              Ash {$HDrive ="U:"}
                          switch ($Site) {
                            Arl {$ou="OU=Users,OU=ARL,OU=NA,OU=company,DC=company,dc=global,dc=pvt"}
                            Ash {$dept = Read-Host "Enter Asheboro Department for $upn. Accounting, Engineering, Human Resources, Information Technology, Manufacturing, or Quality Assurance"
                                 $ou="OU=$dept,OU=Users,OU=ARL,OU=NA,OU=company,DC=company,dc=global,dc=pvt"}
                       $First=$_.GivenName
                       $last=$_.LastName
                       $sam=$first.substring(0,1) + $last
                       $Office=$_.OfficeName
                       $description=$_.Description
                       $street=$_.StreetAddress
                       $city=$_.City
                       $zip=$_.postalcode
                       $state=$_.state
                       $Company=$_.Company
                       $Dept=$_.Department
                       $Title=$_.title
                       $mail=$upn
                       $phone=$_.phone
                       $manager=$_.manager
                       $Location=$_.Country
                       $pass=$_.Password
                       $expires=$_.passwordneverexpires
                       $Enabled=$_.Enabled
                       $setpass = ConvertTo-SecureString -AsPlainText $pass -force
                       $display="$last, $first"
                       Write-Verbose "$sam,$HomeD,$HDrive,$OU,$phone,$site"
    Output when showing my variables and asking for the dept
    VERBOSE: SRogers3,\\share\global\home\medical\na\arl,H:,OU=Users,OU=ARL,OU=NA,OU=company,DC=company,dc=global,dc=pvt,ARL
    Enter Asheboro Department for [email protected] (This should be the user below). Accounting, Engineering, Human Resources, Information Technology, Manufacturing, or Quality Assurance: asdf
    VERBOSE: EScott,\\share2\user,U:,OU=asdf,OU=Users,OU=ARL,OU=NA,OU=company,DC=company,dc=global,dc=pvt,,ASH

    I restructured this and removed some subtle mistakes.  The layout should also be easier to debug.
    function TFX-CreateNewUsers{
    [CmdletBinding()]
    param(
    [string]$logfile='c:\PowerShell_Logs\UserCreationErrors.txt',
    [Switch]$LogErrors,
    [Alias('csv')]
    [Parameter(Mandatory = $true,
    valuefrompipeline = $true,
    HelpMessage = "Please provide valid path and file name to the CSV file with the user information."
    )][string]$FilePath
    $date = Get-Date -Format g
    $addn = (Get-ADDomain).DistinguishedName
    $dnsroot = (Get-ADDomain).DNSRoot
    Import-Csv $FilePath |
    ForEach-Object{
    If($_.GivenName -eq '' -Or $_.LastName -eq ''){
    Write-Host 'ERROR: Please provide valid GivenName, LastName and Initials. Processing stopped' -ForegroundColor Red
    "$date ERROR: Please provide valid GivenName, LastName and Initials. Processing stopped" | Out-File $logfile -Append
    }else{
    $First=$_.GivenName
    $last=$_.LastName
    $sam=$first.substring(0,1) + $last
    $Office=$_.OfficeName
    $description=$_.Description
    $street=$_.StreetAddress
    $city=$_.City
    $zip=$_.postalcode
    $state=$_.state
    $Company=$_.Company
    $Dept=$_.Department
    $Title=$_.title
    $mail=$upn
    $phone=$_.phone
    $manager=$_.manager
    $Location=$_.Country
    $pass=$_.Password
    $expires=$_.passwordneverexpires
    $Enabled=$_.Enabled
    $setpass = ConvertTo-SecureString -AsPlainText $pass -force
    $display="$last, $first"
    $upn="[email protected]"
    if($_.site -eq 'Arl'){
    $HDrive='H:'
    $ou='OU=Users,OU=ARL,OU=NA,OU=company,DC=company,dc=global,dc=pvt'
    $homed='\\share\global\home\medical\na\arl'
    }elseif($_.site -eq 'Ash'){
    $homed='\\share2\user'
    $HDrive='U:'
    $dept=Read-Host "Enter Asheboro Department for $upn. Accounting, Engineering, Human Resources, Information Technology, Manufacturing, or Quality Assurance"
    $ou="OU=$dept,OU=Users,OU=ARL,OU=NA,OU=company,DC=company,dc=global,dc=pvt"
    Write-Verbose $sam,$HomeD,$HDrive,$OU,$phone,$site
    This format for braces helps to prevent errors because the braces do not get lost in the strings like your method does.
    ¯\_(ツ)_/¯

  • How can I display the password expiration date for a user

    I have created a GUI (using PrimalForms) which runs powershel scripts to pull information like user ID, email address, last logon ec. for the helpdesk to help establish the validity of some user claims of "it worked yesterday" and the like.
    I have been asked to add the password expiration date, but I am struggling to get the code for this addition.
    Does anyone know how I can include this, and have it in a human readable format?
    The current scripts (there are 3) allow the helpdesk staff to search on user ID and display name, the third provides the last logon, it was impossible to include this in the other scripts so I added an extra search button and called it good. An example of
    these scripts is below (please note, PrimalForms needs a slightly different syntax in order to get the results displayed, but the core script is standard PS, I use Powershell 3.0)
    $results.Text=Get-ADUser -Filter "sAMAccountName -eq '$($EntryBox.text)'" -Properties DisplayName, sAMAccountName, mail, extensionattribute5, PasswordLastSet, PasswordExpired, PasswordNeverExpires, buMemberOf, telephoneNumber, msExchOmaAdminWirelessEnable, whenCreated, whenChanged, enabled, AccountExpirationDate | select givenName, surname, DisplayName, sAMAccountName, mail, extensionattribute5, PasswordLastSet, PasswordExpired, PasswordNeverExpires, buMemberOf, telephoneNumber, msExchOmaAdminWirelessEnable, whenCreated, whenChanged, enabled, AccountExpirationDate | Out-String
    $results.Focus()
    for info:
    $results.text is the window in the GUI results are displayed  in
    $entrybox.text is the text box the helpdesk staff use to input the user ID or display name of the account they are querying
    $results.focus simply tells the script to put the results in the results.text window
    The screenshot below shows the current setup, this is purely to put the above information into perspective. Obviously some of the information displayed has been removed/redacted along with our logo.

    Hi,
    Here's an example you can build from:
    $maxPasswordAge = 120
    Get-ADUser USER -Properties PasswordLastSet |
    Select SamAccountName,
    PasswordLastSet,
    @{N='PasswordLifeRemaining';E={$maxPasswordAge - ((Get-Date) - $_.PasswordLastSet).Days}},
    @{N='PasswordExpirationDate';E={(Get-Date $_.PasswordLastSet).AddDays($maxPasswordAge)}}
    Don't retire TechNet! -
    (Don't give up yet - 13,085+ strong and growing)

  • NOOB Question - Cannot seem to get the output in a text or CSV file - Please help!!

    I was able to put together a script which finds members of a certain AD group, filters down the users, and then calculates the number of days till a password reset is needed.  I am able to get on screen exactly what i am looking for, but cannot seem
    to figure out how to get the same data to a file.  What i am doing wrong?  two goals here:
    1.  Create a spreadsheet with a list of users whose password is about to expire.
    2.  Down the line automate an email to users whose password is about to expire. 
    Here is my code:
    ## Get List Of Users in Password Change Lockout that do not have an expired password or a password that never expires
    $Names = (Get-ADGroupMember -Identity "Password Change Lockout" -Recursive |`
    Get-ADUser -Properties * |`
    Where-Object {$_.PasswordNeverExpires -eq $False -and $_.PasswordExpired -eq $False} |`
    Sort-Object name |Select-Object -ExpandProperty SamAccountName)
    ## Get Password last Set values for all
    Foreach ($Name in $Names)
    $VAR1 = (Get-ADUserResultantPasswordPolicy -Identity $Name).MaxPasswordAge
    $VAR2 = (Get-ADUser $Name -Properties *).passwordlastset
    $VAR3 = (Get-ADUser $Name -Properties *).name
    $DTPC = (New-TimeSpan -Start (Get-Date) -End ($VAR2 + $VAR1) | Select-Object -ExpandProperty Days)
    Filter users to those who need to change thier password in 15 days.
    If ($DTPC -lt 15)
    No matter what i try between the {} after the If statement, I cannot get the output to a file.  However, if I use a Write-Output I get exactly what i looking for.  I feel like i am forgetting some basic concept and could really use some help.  Thanks.
    Matt 
    Matt Dillon

    Hi Matt,
    I generally create an empty array (something like $out = @()) at the top of the script and then use $out += $desiredOutput inside of the foreach loop.
    Outside of the loop, you can then pipe $out to Out-File or Export-Csv, depending on your needs.
    Don't retire TechNet! -
    (Don't give up yet - 12,830+ strong and growing)

  • How do I correctly append/prepend a description for an AD user?

    I'm still a little new to PowerShell, but experienced enough to be able to search the net and formulate my own script, but I've been stuck on this one part for an entire day now.  Here's what I'm trying to accomplish using PowerShell 4:
    I've already run the following script to produce a list of users in our domain that have not logged into the network for more than 90 days (This is done as a separate requirement of the business):
    search-adaccount -accountinactive -usersonly -timespan "105" | Export-Csv "k:\Inactive90 $(get-date -f yyyy-MM-dd).csv"
    So I have a csv file with the following headers (and data below it, but removed for business privacy):
    AccountExpirationDate Enabled LastLogonDate LockedOut Name ObjectClass ObjectGUID PasswordExpired PasswordNeverExpires UserPrincipalName
    I need to pre-pend the date of disable within the description of the AD user.  The problem that I'm experiencing is that the resultant description that I'm receiving is that the first part of the description is what I expect, where it says
    Last login more than 90 days, Disabled on WHATEVERDATE, but the second part of the description, where I'd expect to see the original description of the AD user, I see this:
    @{Description=PREVIOUS DESCRIPTION TEXT HERE}, so from what I can gather, the original description is getting read as an array, and is thus being output as an array.  So I tried forcing it into a string by putting [string] at the front of the
    $Desc variable.  No dice.
    So the resultant description that I'm currently left with is:
    Last login more than 90 days, Disabled on WHATEVERDATE, @{Description=PREVIOUS DESCRIPTION TEXT HERE}
    I obviously don't want the brackets and @ sign and Description= there.  I'd like it to read as:
    Last login more than 90 days, Disabled on WHATEVERDATE, PREVIOUS DESCRIPTION TEXT HERE
    Below is the code for a script that I've written.  Any help is much appreciated.
    $cred = Get-Credential
    $Date = Get-Date -UFormat %D
    $InactiveUsers = Import-csv ".\test.csv"
    foreach ($User in $InactiveUsers)
    Disable-ADAccount -Identity $User.ObjectGUID -Credential $cred
    $Desc = Get-ADUser -Identity $User.ObjectGUID -Properties Description -Credential $cred | Select-Object -Property Description
    Set-ADUser -Identity $User.ObjectGUID -Credential $cred -Description "Last login more than 90 days, Disabled on $Date, $Desc"

    This should work:
    $cred = Get-Credential
    $Date = Get-Date -UFormat %D
    $InactiveUsers = Import-csv ".\test.csv"
    foreach ($User in $InactiveUsers)
    Disable-ADAccount -Identity $User.ObjectGUID -Credential $cred
    $Desc = Get-ADUser -Identity $User.ObjectGUID -Properties Description -Credential $cred | Select-Object -ExpandProperty Description
    Set-ADUser -Identity $User.ObjectGUID -Credential $cred -Description "Last login more than 90 days, Disabled on $Date, $Desc"
    Instead of
    Select -Property Description
    use
    Select -ExpandProperty Description
    that will give you the actual data of the property instead of what is called a NoteProperty that gives you the brackets.
    I hope this post has helped!

  • Creating new user in AD

    Hi all,
    I am trying to write a script to create new user in Active Directory using power-shell
    $sam = "13653123"
    try{
    get-aduser -Identity $sam -ErrorAction Stop
    catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]
    $error1= [System.Windows.Forms.MessageBox]::Show("ERROR : Account Not found")
    $SamAccountName = $sam
    $gn = "Jack Sparrow"
    $Initials = "ZX"
    $dn = "$gn "+" $Initials"
    $Department = "1260"
    $title = "AM"
    $pwd1 = read-host "Please enter the password"
    $pwd2 = read-host "Please enter the password"
    if($pwd1 -eq $pwd2)
    $pwd = $pwd1 = $pwd2
    try
    $userprinicpalname = $SamAccountName + "@XXX.com"
    New-ADUser -SamAccountName $SamAccountName -UserPrincipalName $userprinicpalname -GivenName $gn -Initials $Initials -Name $dn -DisplayName $dn -Title $title -Department $Department -Office $Department -Path "OU=XXXX,DC=XXX,DC=com" -AccountPassword (ConvertTo-SecureString $pwd -AsPlainText -force) -Enabled $True -PasswordNeverExpires $False -ErrorAction Stop
    catch [Microsoft.ActiveDirectory.Management.ADPasswordComplexityException]
    $error7= [System.Windows.Forms.MessageBox]::Show("ERROR : The password you entered doesnot meet the complexity set in the Password Policy" )
    break
    else
    $error2= [System.Windows.Forms.MessageBox]::Show("ERROR : passwords donot match")
    I am getting issue when The password complexity error is coming. It is showing up the error in the catch, but it is creating the account in AD and disabling it. 
    What I want is if any error is found and caught in the catch, then the user should not be created. How to do that?
    Please provide your valuable suggestions and help me out
    Naveen Basati

    This is a good way to get teh paassword to abort when it fails the test.
    function Test-Password{
    Param($Password)
    Try{
    $pwd=ConvertTo-SecureString $Password -AsPlainText -force
    Set-ADAccountPassword testuser11 -NewPassword $pwd –Reset
    # it worked so return the encrypted password
    $pwd
    Catch{
    Throw $_
    $sam = "13653123"
    if(get-aduser -Filter "SamAccountName -eq $sam"){
    Write-Host 'User already exists' -ForegroundColor green
    }else{
    Try{
    $pwdText='x123!heLno34' # 3 levels of compexity plus length > 9
    $pwd=Test-Password $pwdText
    $given='Jack'
    $surname='Sparrow'
    $Initials='Z'
    $Department='1260'
    $title='AM'
    $props=@{
    SamAccountName=$sam
    UserPrincipalName="$[email protected]"
    GivenName=$given
    Initials=$Initials
    Name="$given $initials $surname"
    DisplayName="$given $initials $surname"
    Title=$title
    Department=$Department
    Office=$Department
    Path='OU=TestOU,DC=testnet,DC=local'
    AccountPassword=$pwd
    Enabled=$True
    PasswordNeverExpires=$False
    New-ADUser @props -ErrorAction Stop
    Catch{
    throw $_
    We just re-throw the error and it propagates to the outer try/catch block.
    ¯\_(ツ)_/¯

  • Bulk Create Users from CSV: Error: "Put": "There is no such object on the server."?

    Hi,
    I'm using the below PowerShell script, by @hicannl which I found on the MS site, for bulk creating users from a CSV file.
    I've had to edit it a bit, adding some additional user fields, and removing others, and changing the sAMAccount name from first initial + lastname, to firstname.lastname. However now when I run it, I get an error saying:
    "[ERROR]     Oops, something went wrong: The following exception occurred while retrieving member "Put": "There is no such object on the server."
    The account is created in the default OU, with the correct firstname.lastname format, but then it seems to error at setting the "Set an ExtensionAttribute" section. However I can't see why!
    Any help would be appreciated!
    # ERROR REPORTING ALL
    Set-StrictMode -Version latest
    # LOAD ASSEMBLIES AND MODULES
    Try
    Import-Module ActiveDirectory -ErrorAction Stop
    Catch
    Write-Host "[ERROR]`t ActiveDirectory Module couldn't be loaded. Script will stop!"
    Exit 1
    #STATIC VARIABLES
    $path = Split-Path -parent $MyInvocation.MyCommand.Definition
    $newpath = $path + "\import_create_ad_users_test.csv"
    $log = $path + "\create_ad_users.log"
    $date = Get-Date
    $addn = (Get-ADDomain).DistinguishedName
    $dnsroot = (Get-ADDomain).DNSRoot
    $i = 1
    $server = "localserver.ourdomain.net"
    #START FUNCTIONS
    Function Start-Commands
    Create-Users
    Function Create-Users
    "Processing started (on " + $date + "): " | Out-File $log -append
    "--------------------------------------------" | Out-File $log -append
    Import-CSV $newpath | ForEach-Object {
    If (($_.Implement.ToLower()) -eq "yes")
    If (($_.GivenName -eq "") -Or ($_.LastName -eq ""))
    Write-Host "[ERROR]`t Please provide valid GivenName, LastName. Processing skipped for line $($i)`r`n"
    "[ERROR]`t Please provide valid GivenName, LastName. Processing skipped for line $($i)`r`n" | Out-File $log -append
    Else
    # Set the target OU
    $location = $_.TargetOU + ",$($addn)"
    # Set the Enabled and PasswordNeverExpires properties
    If (($_.Enabled.ToLower()) -eq "true") { $enabled = $True } Else { $enabled = $False }
    If (($_.PasswordNeverExpires.ToLower()) -eq "true") { $expires = $True } Else { $expires = $False }
    If (($_.ChangePasswordAtLogon.ToLower()) -eq "true") { $changepassword = $True } Else { $changepassword = $False }
    # A check for the country, because those were full names and need
    # to be land codes in order for AD to accept them. I used Netherlands
    # as example
    If($_.Country -eq "Netherlands")
    $_.Country = "NL"
    ElseIf ($_.Country -eq "Austria")
    $_.Country = "AT"
    ElseIf ($_.Country -eq "Australia")
    $_.Country = "AU"
    ElseIf ($_.Country -eq "United States")
    $_.Country = "US"
    ElseIf ($_.Country -eq "Germany")
    $_.Country = "DE"
    ElseIf ($_.Country -eq "Italy")
    $_.Country = "IT"
    Else
    $_.Country = ""
    # Replace dots / points (.) in names, because AD will error when a
    # name ends with a dot (and it looks cleaner as well)
    $replace = $_.Lastname.Replace(".","")
    $lastname = $replace
    # Create sAMAccountName according to this 'naming convention':
    # <FirstName>"."<LastName> for example
    # joe.bloggs
    $sam = $_.GivenName.ToLower() + "." + $lastname.ToLower()
    Try { $exists = Get-ADUser -LDAPFilter "(sAMAccountName=$sam)" -Server $server }
    Catch { }
    If(!$exists)
    # Set all variables according to the table names in the Excel
    # sheet / import CSV. The names can differ in every project, but
    # if the names change, make sure to change it below as well.
    $setpass = ConvertTo-SecureString -AsPlainText $_.Password -force
    Try
    Write-Host "[INFO]`t Creating user : $($sam)"
    "[INFO]`t Creating user : $($sam)" | Out-File $log -append
    New-ADUser $sam -GivenName $_.GivenName `
    -Surname $_.LastName -DisplayName ($_.LastName + ", " + $_.GivenName) `
    -StreetAddress $_.StreetAddress -City $_.City `
    -Country $_.Country -UserPrincipalName ($sam + "@" + $dnsroot) `
    -Company $_.Company -Department $_.Department `
    -Title $_.Title -AccountPassword $setpass `
    -PasswordNeverExpires $expires -Enabled $enabled `
    -ChangePasswordAtLogon $changepassword -server $server
    Write-Host "[INFO]`t Created new user : $($sam)"
    "[INFO]`t Created new user : $($sam)" | Out-File $log -append
    $dn = (Get-ADUser $sam).DistinguishedName
    # Set an ExtensionAttribute
    If ($_.ExtensionAttribute1 -ne "" -And $_.ExtensionAttribute1 -ne $Null)
    $ext = [ADSI]"LDAP://$dn"
    $ext.Put("extensionAttribute1", $_.ExtensionAttribute1)
    Try { $ext.SetInfo() }
    Catch { Write-Host "[ERROR]`t Couldn't set the Extension Attribute : $($_.Exception.Message)" }
    # Move the user to the OU ($location) you set above. If you don't
    # want to move the user(s) and just create them in the global Users
    # OU, comment the string below
    If ([adsi]::Exists("LDAP://$($location)"))
    Move-ADObject -Identity $dn -TargetPath $location
    Write-Host "[INFO]`t User $sam moved to target OU : $($location)"
    "[INFO]`t User $sam moved to target OU : $($location)" | Out-File $log -append
    Else
    Write-Host "[ERROR]`t Targeted OU couldn't be found. Newly created user wasn't moved!"
    "[ERROR]`t Targeted OU couldn't be found. Newly created user wasn't moved!" | Out-File $log -append
    # Rename the object to a good looking name (otherwise you see
    # the 'ugly' shortened sAMAccountNames as a name in AD. This
    # can't be set right away (as sAMAccountName) due to the 20
    # character restriction
    $newdn = (Get-ADUser $sam).DistinguishedName
    Rename-ADObject -Identity $newdn -NewName ($_.LastName + ", " + $_.GivenName)
    Write-Host "[INFO]`t Renamed $($sam) to $($_.GivenName) $($_.LastName)`r`n"
    "[INFO]`t Renamed $($sam) to $($_.GivenName) $($_.LastName)`r`n" | Out-File $log -append
    Catch
    Write-Host "[ERROR]`t Oops, something went wrong: $($_.Exception.Message)`r`n"
    Else
    Write-Host "[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) already exists or returned an error!`r`n"
    "[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) already exists or returned an error!" | Out-File $log -append
    Else
    Write-Host "[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) will be skipped for processing!`r`n"
    "[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) will be skipped for processing!" | Out-File $log -append
    $i++
    "--------------------------------------------" + "`r`n" | Out-File $log -append
    Write-Host "STARTED SCRIPT`r`n"
    Start-Commands
    Write-Host "STOPPED SCRIPT"

    Here is one I have used.  It can be easily updated to accommodate many needs.
    function New-RandomPassword{
    $pwdlength = 10
    $bytes = [byte[]][byte]1
    $pwd=[string]""
    $rng=New-Object System.Security.Cryptography.RNGCryptoServiceProvider
    while (!(($PWD -cmatch "[a-z]") -and ($PWD -cmatch "[A-Z]") -and ($PWD -match "[0-9]"))){
    $pwd=""
    for($i=1;$i -le $pwdlength;$i++){
    $rng.getbytes($bytes)
    $rnd = $bytes[0] -as [int]
    $int = ($rnd % 74) + 48
    $chr = $int -as [char]
    $pwd = $pwd + $chr
    $pwd
    function AddUser{
    Param(
    [Parameter(Mandatory=$true)]
    [object]$user
    $pwd=New-RandomPassword
    $random=Get-Random -minimum 100 -maximum 999
    $surname="$($user.Lastname)$random"
    $samaccountname="$($_.Firstname.Substring(0,1))$surname"
    $userprops=@{
    Name=$samaccountname
    SamAccountName=$samaccountname
    UserPrincipalName=“$[email protected]”)
    GivenName=$user.Firstname
    Surname=$surname
    SamAccountName=$samaccountname
    AccountPassword=ConvertTo-SecureString $pwd -AsPlainText -force
    Path='OU=Test,DC=nagara,DC=ca'
    New-AdUser @userprops -Enabled:$true -PassThru | |
    Add-Member -MemberType NoteProperty -Name Password -Value $pwd -PassThru
    Import-CSV -Path c:\users\administrator\desktop\users.csv |
    ForEach-Object{
    AddUser $_
    } |
    Select SamAccountName, Firstname, Lastname, Password |
    Export-Csv \accountinformation.csv -NoTypeInformation
    ¯\_(ツ)_/¯

  • Only the last account is created when using this script in combination with a CSV

    Hi, I've got a weird problem when using this script:
    $Users = Import-Csv -Delimiter ";" -Path "......csv"  
    FOREACH ($User in $UserList) { $ User }
        $OU = $User.path
        $UPN = $User.UPN
        $Password = $User.password 
        $Detailedname = $User.firstname + " " + $User.Lastname 
        $UserFirstname = $User.Firstname 
        $FirstLetterFirstname = $UserFirstname.substring(0,1) 
        $SAM =  $User.UPN
        $Company = $User.company
        $Description = $User.description
        $AccountExpirationDate = $User.accountexpirationdate
    $params = @{ 'Name'=$Detailedname;
                 'SamAccountName'=$SAM;
                 'UserPrincipalName'=$SAM;
                 'DisplayName'=$Detailedname;
                 'GivenName'=$UserFirstname;
                 'Surname'=$User.Lastname;
                 'AccountPassword'=(ConvertTo-SecureString $Password -AsPlainText -Force);
                 'Enabled'=$True;
                 'PasswordNeverExpires'=$True;
                 'Path'=$OU;
                 'Company'=$Company;
                 'Description'=$Description;
                 'AccountExpirationDate'=$AccountExpirationDate }
    New-ADUser @params
    The CSV file has columns with the name: Lastname;Firstname;Password;Company;Description;UPN;path;AccountExpirationDate
    Script runs without errors, but only creates the last line in the CSV file. Anyone that can help me, of put me in the right direction? Should be great!
    Michiel
    the Netherlands

    Hi Michiel,
    You'll need to move $params and New-ADUser up into the foreach loop.
    EDIT: Also, remove the { $ User } that you have next to the foreach loop. You're also using $Users instead of $UserList.
    EDIT2: Here's a cleaned up version:
    $UserList = Import-Csv -Delimiter ";" -Path "......csv"
    FOREACH ($User in $UserList) {
    $OU = $User.path
    $UPN = $User.UPN
    $Password = $User.password
    $Detailedname = $User.firstname + " " + $User.Lastname
    $UserFirstname = $User.Firstname
    $FirstLetterFirstname = $UserFirstname.substring(0,1)
    $SAM = $User.UPN
    $Company = $User.company
    $Description = $User.description
    $AccountExpirationDate = $User.accountexpirationdate
    $params = @{ 'Name'=$Detailedname;
    'SamAccountName'=$SAM;
    'UserPrincipalName'=$SAM;
    'DisplayName'=$Detailedname;
    'GivenName'=$UserFirstname;
    'Surname'=$User.Lastname;
    'AccountPassword'=(ConvertTo-SecureString $Password -AsPlainText -Force);
    'Enabled'=$True;
    'PasswordNeverExpires'=$True;
    'Path'=$OU;
    'Company'=$Company;
    'Description'=$Description;
    'AccountExpirationDate'=$AccountExpirationDate
    New-ADUser @params
    Don't retire TechNet! -
    (Don't give up yet - 13,085+ strong and growing)

  • OOTB create user is not working for AD

    Hi,
    While creating the user am getting the following error.
    [6/1/11 0:33:28:153 EDT] 00000037 SystemOut O DEBUG,01 Jun 2011 00:33:28,153,[XELLERATE.ADAPTERS],Class/Method: tcAdpEvent/getRunTimeVariableMappings - Data: adv name - Value: PasswordNeverExpires
    [6/1/11 0:33:28:153 EDT] 00000037 SystemOut O DEBUG,01 Jun 2011 00:33:28,153,[XELLERATE.ADAPTERS],Class/Method: tcAdpEvent/getRunTimeVariableMappings left.
    [6/1/11 0:33:28:153 EDT] 00000037 SystemOut O DEBUG,01 Jun 2011 00:33:28,153,[XELLERATE.ADAPTERS],Class/Method: tcAdpEvent/getRunTimeValue - Data: Variable Name - Value: PasswordNeverExpires
    [6/1/11 0:33:28:153 EDT] 00000037 SystemOut O DEBUG,01 Jun 2011 00:33:28,153,[XELLERATE.ADAPTERS],Class/Method: tcAdpEvent/getRunTimeValue - Data: MapTo - Value: Process Data
    [6/1/11 0:33:28:153 EDT] 00000037 SystemOut O DEBUG,01 Jun 2011 00:33:28,153,[XELLERATE.ADAPTERS],Class/Method: tcAdpEvent/getRunTimeValue - Data: sMapQualifier - Value: Password never expires
    [6/1/11 0:33:28:153 EDT] 00000037 SystemOut O DEBUG,01 Jun 2011 00:33:28,153,[XELLERATE.ADAPTERS],Class/Method: tcAdpEvent/getRunTimeValue - Data: sMapValue - Value: UD_ADBURG_NEVER
    [6/1/11 0:33:28:153 EDT] 00000037 SystemOut O DEBUG,01 Jun 2011 00:33:28,153,[XELLERATE.ADAPTERS],Class/Method: tcAdpEvent/getRunTimeValue - Data: sVarDataType - Value: Boolean
    [6/1/11 0:33:28:153 EDT] 00000037 SystemOut O DEBUG,01 Jun 2011 00:33:28,153,[XELLERATE.ADAPTERS],Class/Method: tcAdpEvent/getRunTimeValue - Data: sMapOldValue - Value: 0
    [6/1/11 0:33:28:153 EDT] 00000037 SystemOut O DEBUG,01 Jun 2011 00:33:28,153,[XELLERATE.ADAPTERS],Class/Method: tcAdpEvent/getRunTimeValue - Data: sMapChildTableName - Value:
    [6/1/11 0:33:28:153 EDT] 00000037 SystemOut O DEBUG,01 Jun 2011 00:33:28,153,[XELLERATE.ADAPTERS],Class/Method: tcAdpEvent/getDataSetFieldValue entered.
    [6/1/11 0:33:28:153 EDT] 00000037 SystemOut O DEBUG,01 Jun 2011 00:33:28,153,[XELLERATE.ADAPTERS],Class/Method: tcAdpEvent/getDataSetFieldValue - Data: psFieldName - Value: UD_ADBURG_NEVER
    [6/1/11 0:33:28:153 EDT] 00000037 SystemOut O DEBUG,01 Jun 2011 00:33:28,153,[XELLERATE.ADAPTERS],Class/Method: tcAdpEvent/getDataSetFieldValue - Data: psMapSourceDataType - Value: Boolean
    [6/1/11 0:33:28:153 EDT] 00000037 SystemOut O DEBUG,01 Jun 2011 00:33:28,153,[XELLERATE.ADAPTERS],tcAdpEvent/getDataSetFieldValue poDataSet is null
    [6/1/11 0:33:28:157 EDT] 00000037 SystemOut O DEBUG,01 Jun 2011 00:33:28,157,[XELLERATE.ADAPTERS],Class/Method: tcAdpEvent/updateSchItem entered.
    [6/1/11 0:33:28:157 EDT] 00000037 SystemOut O DEBUG,01 Jun 2011 00:33:28,157,[XELLERATE.ADAPTERS],Class/Method: tcAdpEvent/updateSchItem - Data: event - Value: adpADCSCREATEUSER
    [6/1/11 0:33:28:157 EDT] 00000037 SystemOut O DEBUG,01 Jun 2011 00:33:28,157,[XELLERATE.ADAPTERS],Class/Method: tcAdpEvent/updateSchItem - Data: New Status - Value: R
    [6/1/11 0:33:28:157 EDT] 00000037 SystemOut O DEBUG,01 Jun 2011 00:33:28,157,[XELLERATE.ADAPTERS],Class/Method: tcAdpEvent/updateSchItem - Data: SchData - Value: {2}
    *[6/1/11 0:33:28:157 EDT] 00000037 SystemOut O DEBUG,01 Jun 2011 00:33:28,157,[XELLERATE.ADAPTERS],Class/Method: tcAdpEvent/updateSchItem - Data: Reason - Value: Exception java.lang.NullPointerException was thrown in adapter "ADCS Create User". The Adapter Response was "null"*
    NOTE:
    Am creating user through the access policy, it throwing the above error for auto provisioning…
    IF open (edit) process form of AD and click on save (w/o changing the process data) and retrying the crate user task it working .
    Advance Thanks..

    This is typically the result of the checkboxes on the form. You need to give a default value of 0 or 1 either using the Default option, or prepopulate. If you do not fill this in, when the form is completed through auto-save, it will have a null value.
    -Kevin

  • Importing a CSV file into AD 2012r2

    Hi Guys
    Just wondering if anyone can help, I am a newbie on scripting and finding it really difficult to understand how to import a csv file into AD
    I have created the CSV file with the following headers, see below but I am unable to write a powershell script to import them into AD which work, I have tried multiple help guides but still cannot do it for the life of me.
    Any help on this would be really appreciated 
    objectClass user
    cn Jo bloggs
    givenName jo
    sn blogs
    mail [email protected]
    sAMAccountname j.blogs
    AccountPassword Pa$$w0rd
    ChangePasswordAtLogon true
    PasswordNeverExpires false
    ou OU=staff,DC=test,DC=com

    Import-Csv C:\User.csv| %{New-ADUser -SamAccountName $_.SamAccountName `
    -UserPrincipalName $_.userprinicpalname `
    -Name $_.name `
    -Mail = $_.mail `
    -DisplayName $_.name `
    -GivenName $_.GivenName `
    -Path "OU=Test Users,DC=XXX,DC=XXX" `
    -PasswordNeverExpires $false `
    -ChangePasswordAtLogon $true `
    -AccountPassword (ConvertTo-SecureString "test41;" -AsPlainText -force) `
    -Enabled $True -PasswordNeverExpires $True -PassThru ` }
    help New-ADUser -Examples
    You can try the below sample code
    Regards Chen V [MCTS SharePoint 2010]

  • Script should wait until the user is reflected in AD.

    Hi,
    I have made a script which makes mail enabled user in Exchange and update the other attributes in AD. I have put the delay between two commands so that it can give enough time to replicate in AD. However i have seen that sometimes its taking more time and
    script gives error that can not find user under domain and it don't updates the attributes.
    Is there any way to resolve this issue ? Like powershell will execute the next command once it found the user in AD.
    new-mailuser -FirstName $First.Trim() -LastName $Last.Trim() -Name $Displayname.Trim() -alias $UserName.Trim() -ExternalEmailAddress $Email.Trim() -userPrincipalName  $UPN -OrganizationalUnit $OUpath -Password (ConvertTo-SecureString $Passwd.Trim()
    -AsPlainText -Force)
    start-sleep -Seconds 20
    Set-ADUser -Identity $UserName.Trim() -company $Company.trim() -Description $desc.trim() -PasswordNeverExpires $True -manager $Manager.Trim()
    set-qaduser -Identity $UserName.Trim() -Notes $Ticket
    Shaktisinh Vaghela

    You could do something like this:
    while (-not $ADUser) {
    try {$ADUser = Get-ADUser $UserName.Trim()}
    catch {Write-Output "User not found in AD yet. Sleeping for 5 seconds..."; sleep 5}
    I had to wrap the Get-ADUser command in a Try-Catch statement as it's the only way that I know of to suppress a terminating error. 
    The only annoying thing about this method is that the script will sleep for 5 seconds, even if it finds the user in AD straight away. This is because $ADUser is null the first time around when it's evaluated in the While loop.

Maybe you are looking for

  • PDF disapppears in Preview PDF tab

    hi i am completely new to LCD ES2. i downloaded the train version today and after installing the trail version created a new blank form and placed a checkbox on the form and then tried to preview the form using the "Preview PDF" tab but surprisingly

  • Error uploading iphoto book

    I am using iphoto 6.0.4. I keep getting an error while trying to upload pictures. It assembles the book okay then always gets stuck at "transferring 119k of 15.1 MB" for a while then an error message pops up saying there was an error with one of the

  • How do I get rid of a virus on my MAC

    I downloaded this "movie player" it let me watch the movie, but right after I got a bunch of pop up ads and it opens new tabs up with different ads, help!

  • Get Workflow protocol

    Hello. for our workflow regarding Purchase Order release strategy we need to know which agent has processed the last release (=Workitem). Now i found FM "SAP_WAPI_DIALOG_PROTOCOL". This FM shows up the needed information in tab "Workflow objects" in

  • Overlay in Viewer will not Display

    I just made a clean install of Leopard (just kept my Aperture Libary) - installed Aperture 1.5.0 and updated to 1.5.6. Now I miss two things - the "view setups" - for keywording - viewing ect. and the overlay Infos will not display. I reinstalled Ape