header image

Using AccountManagement classes to set local accounts expiry

Posted by: | July 15, 2011 | 2 Comments |

This is a little more verbose than the WinNT example

function set-expirydate {            
[CmdletBinding(SupportsShouldProcess=$true)]            
param (            
 [parameter(ValueFromPipeline=$true,            
   ValueFromPipelineByPropertyName=$true)]            
 [string]$computer,            
             
 [parameter(ValueFromPipeline=$true,            
   ValueFromPipelineByPropertyName=$true)]            
 [string]$id              
)            
BEGIN {Add-Type -AssemblyName System.DirectoryServices.AccountManagement}             
PROCESS {               
 switch ($computer){            
  "."    {$computer = $env:computername}            
  "localhost" {$computer = $env:computername}            
 }            
             
 $ctype = [System.DirectoryServices.AccountManagement.ContextType]::Machine            
 $context = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext `
    -ArgumentList $ctype, $computer            
            
 $user = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($context, $id)            
             
## set the expiry date            
if ($psCmdlet.ShouldProcess("$id", "Expiry date set ")) {            
    $user.AccountExpirationDate = (Get-Date).AddDays(2)            
    $user.Save()            
  }            
}              
}

Set the context to machine and use the machine name to define which machine.  Find the user and set the AccountExpirationDate property then save

under: IT Security, PowerShell and Active Directory, Windows 7, Windows Server 2008, Windows Server 2008 R2

2 Comments

  1. By: Serge Nikalaichyk on July 15, 2011 at 7:56 am      

    Hello! Are you planning to implement -Credential parameter in AccountManagement-related functions?

  2. By: RichardSiddaway on July 15, 2011 at 8:32 am      

    I haven’t because I am either using them locally or in a domain setting. Its easy enough to do so I’ll add it in before publishing the function set