Wednesday, 22 June 2016

Extracting Active Directory accounts into SAS using Powershell

Having a list of domain users and associated properties can be useful for a number of reasons:

  • Identifying joiners / leavers
  • Getting a list of employees
  • Converting usernames into email addresses
  • Alerting administrators when accounts are locked out
Below is an approach for obtaining those users, producing a SAS dataset that could serve in a DI job for staging a database table.
/* set up command via pipe fileref */
options noquotelenmax;
filename process pipe
  "powershell ""Get-ADUser -Filter {enabled -eq $True} -properties Title,LockedOut,Created,Department,EmailAddress
  |Select-Object SamAccountName,Name,GivenName,Surname,UserPrincipalName,DistinguishedName,Title,LockedOut,created,Department,EmailAddress
  |Export-CSV  '%sysfunc(pathname(work))\ad_users.csv' "" ";

/* execute command and capture any output from the shell */
data _null_;
  infile process;

/* load CSV into SAS dataset */
data AD_USERS;
  infile "%sysfunc(pathname(work))\ad_users.csv" dsd
    firstobs=3 lrecl=10000;
  input SamAccountName:$100. name:$100. GivenName:$50.
    SurName:$50. UserPrincipalName:$200.
    DistinguishedName:$500. Title:$100. LockedOut:$5.
    created:$25. Department:$50. EmailAddress:$100.;
  if index(DistinguishedName,'OU=Employees') then EMPLOYEE_FLG=1;
  else EMPLOYEE_FLG=0;

This will extract all ACTIVE accounts (enabled eq $True) with some selected additional properties (more here).  Some conditional logic is applied to distinguish employees from service accounts.

  • X Command enabled (see here for instructions, is similar process for workspace servers)
  • Powershell installed