Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Null troubles with PowerShell AD script for creating new users

Been smooth sailing with creating users for my domain, now I’m trying to set the uidNumber based on what the last 4 digits of the generated objectSid. Might be a simple solution but hoping for some help.

The rest of the code runs fine until we get to the ‘$last4’ variable so I snipped to make it shorter, but if putting the whole script helps, happy to do so.

Import-Module ActiveDirectory

$firstname = Read-Host -Prompt "Please enter the first name"
$lastname = Read-Host -Prompt "Please enter the last name"

$location = Read-Host -Prompt "Please enter user location (LA/NY)"
$path = "OU=Users,OU=$location,OU=GS,DC=random,DC=com"

New-ADUser `
   -snip

Add-ADGroupMember `
    -Identity "$snip" -Members $username

$user = Get-ADUser -Identity $username

$objectSid = $user.objectSid

$last4DigitsOfObjectSid = $objectSid.Substring($objectSid.Length - 4)
$newUidNumber = "71$last4DigitsOfObjectSid"

Set-ADUser -Identity $username -Replace @{'uidNumber'=$newUidNumber}

Error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You cannot call a method on a null-valued expression.
At C:\Users\Administrator\Desktop\newtry.ps1:31 char:1

  • $last4DigitsOfObjectSid = $objectSid.Substring($objectSid.Length – 4)

CategoryInfo : InvalidOperation: (:) [], RuntimeException
FullyQualifiedErrorId : InvokeMethodOnNull

>Solution :

objectSid is not an attribute that Get-ADUser returns by default, the attribute you’re looking for is just SID. $objectSid in your snippet is actually null, hence the error you’re having.

Also, Substring is a String method and SID and objectSid are instances of SecurityIdentifier. This class does not have a Substring method. You would need to refer to the .Value property:

$sid = $user.SID
$last4DigitsOfObjectSid = $sid.Value.Substring($sid.Value.Length - 4)

A much easier way of getting the last 4 digits would be with -replace which will coerce the SecurityIdentifier to a string before replacing:

$sid = $user.SID
$last4DigitsOfObjectSid = $sid -replace '.+(?=.{4}$)'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading