new-LocalUser: Object reference not set to an instance of an object.

Abo Ashkhatoyan 86 Reputation points
2022-08-26T10:24:09.937+00:00

Hi all I have script that creating local user and adding him to Admin group
Start-Transcript

$UserName = Read-Host "Username"  
$Password = Read-Host "Password" -AsSecureString  
Write-Host $UserName -Debug  
Write-Host $Password - debug  
New-LocalUser -Name $UserName -Password $Password -description 'NewUser'  
Add-LocalGroupMember -Group "Administrators" -Member ("$Username") -Verbose   
Start-Sleep 60  

Its work correctly while running using Visual studio code. I need create from this script .exe file. I'm using Ps2.exe module but when trying run exe file it gives me

ERROR: Object reference not set to an instance of an object.  
ERROR: Object reference not set to an instance of an object.  

Actually errors are on lines`
New-LocalUser
Add-LocalGroupMember
Cant find where is problem can somebody help me with this ?

Windows for business Windows Client for IT Pros Devices and deployment Set up, install, or upgrade
Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. MotoX80 36,291 Reputation points
    2022-08-26T13:59:41.07+00:00

    I'm using Ps2.exe

    Save the code as a .ps1 file and run it using powershell.exe. If that works, then there must be some bug in ps2.exe.

    0 comments No comments

  2. Limitless Technology 39,916 Reputation points
    2022-09-01T07:17:11.24+00:00

    Hello there,

    This error message might occur if you are not running powershell as admin or powershell has been corrupted. Try to reinstall powershell and check the code

    Some variable or function’s return value is null, maybe in your part of code.

    The below thread discusses the same issue and you can try out some troubleshooting steps from this and see if that helps you to sort the Issue.

    https://learn.microsoft.com/en-us/answers/questions/276898/getting-error-34object-reference-not-set-to-an-ins.html

    -----------------------------------------------------------------------------------------------------------------------------------

    --If the reply is helpful, please Upvote and Accept it as an answer--

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.