Categories

Using AccountManagement classes to set local accounts expiry

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

2 Responses to Using AccountManagement classes to set local accounts expiry

Leave a Reply