Powersell: Object Referance not set an instance of an object

Albert Ashkhatoyan 21 Reputation points

Hi all.
I have ps1 script that creating local user and adding to admins group when I'm run it in Visual Studio code or Powershell Ise its working correct.

$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 30  

But when I'm trying to create exe file using Ps2exe module that gives me error what you can face in attachment 235791-error.jpg

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,354 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. MotoX80 31,561 Reputation points

    Please see my answer your first question.


    Save the script as a .ps1 file. Execute it with Powershell.exe. If that works, then there is nothing wrong with either the script or Powershell itself. In that case you will need to contact the author of the Ps2exe program and ask them for help.

    Are you using the current version? Maybe try a different version.


    1 person found this answer helpful.
    0 comments No comments

  2. Michael Taylor 47,711 Reputation points

    I cannot imagine why you would want to convert your PS files to EXEs. PS is on every version of Windows now so just use PS directly. If for some reason you cannot use PS then just create the corresponding C# code and compile it. The program is just using PS through a wrapper that is a wrapper of another wrapper around the PS runtime. This seems like a fragile approach to avoiding scripting when there are better tools available. As mentioned in their readme, it is also being flagged as a virus and sending your scripts (every time you make changes I'd wager) isn't really a feasible approach.

    My theory is that this tool isn't automatically loading modules like PS does. PS will automatically import modules when you reference cmdlets from them (e.g. New-LocalUser). It makes working with PS easier but I suspect the tool's wrapper's wrapper doesn't handle that so it is failing. You can try adding the explicit import's needed to use the New-LocalUser and other cmdlets. But I don't know that it will solve the problem. I did notice they support generating debug information as well so maybe you should turn that feature on.

    0 comments No comments