How to Use PowerShell to Set Local Administrator Passwords

The world of IT is ever-evolving, with continuous demands to maintain security and optimal operation of systems. A vital aspect of these operations is the management of user credentials, especially for administrator accounts. Today’s topic focuses on a PowerShell script that aids in setting local administrator passwords, an essential task for IT professionals.

Background

User credentials are the gatekeepers of access within a system. The administrator password, being a high-level access credential, often demands timely changes to ensure system security. IT professionals and Managed Service Providers (MSPs) regularly engage in tasks that necessitate modifications of these passwords. The provided script simplifies this procedure, making it efficient and error-free.

The Script

#Requires -Version 5.1

<#
.SYNOPSIS
    Sets the local Administrator password.
.DESCRIPTION
    Sets the local Administrator password, or other username.
.EXAMPLE
     -Password "Somepass1"
    Set's the local Administrator account's password to Somepass1
.EXAMPLE
     -UserName "Admin1" -Password "Somepass1"
    Set's the local Administrator account's password to Somepass1, but the account name is Admin1
.EXAMPLE
    PS C:> Set-LocalAdminPassword.ps1 -Password "Somepass1"
    Set's the local Administrator account's password to Somepass1
.OUTPUTS
    None
.NOTES
    Minimum OS Architecture Supported: Windows 10, Windows Server 2016
    Release Notes:
    Initial Release
 By using this script, you indicate your acceptance of the following legal terms as well as our Terms of Use at https://www.ninjaone.com/terms-of-use.
    Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms. 
    Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party. 
    Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library or website belonging to or under the control of any other software provider. 
    Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations. 
    Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks. 
    Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script. 
    EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).
.COMPONENT
    LocalUserAccountManagement
#>

[CmdletBinding()]
param (
    [Parameter()]
    [String]
    $UserName = "Administrator",
    [String]
    $Password
)

begin {
    function Test-IsElevated {
        $id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
        $p = New-Object System.Security.Principal.WindowsPrincipal($id)
        if ($p.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator))
        { Write-Output $true }
        else
        { Write-Output $false }
    }
}
process {
    if (-not (Test-IsElevated)) {
        Write-Error -Message "Access Denied. Please run with Administrator privileges."
        exit 1
    }
    if ($PSVersionTable.PSVersion.Major -le 2) {
        & net.exe $UserName $Password
        if ($LASTEXITCODE -gt 0) {
            $Password = $null
            exit $LASTEXITCODE
        }
    }
    else {
        try {
            Set-LocalUser -Name $UserName -Password (ConvertTo-SecureString -String $Password -AsPlainText -Force) -Confirm:$false
        }
        catch {
            Write-Error $_
            $Password = $null
            exit 1
        }
    }
}
end {
    $Password = $null
}

 

Access 300+ scripts in the NinjaOne Dojo

Get Access

Detailed Breakdown

Let’s dissect the script for a clearer understanding:

  • Metadata Section: This portion provides a synopsis, description, examples of how to use the script, outputs, notes, and components. It gives an instant overview to anyone looking at the script for the first time.
  • Cmdlet Binding and Parameters: The script utilizes a cmdlet binding, enhancing its functionality with advanced features. It takes two parameters:
  • $UserName: Specifies which user’s password to change, defaulting to “Administrator”.
  • $Password: The new password.
  • Begin Block: A function, Test-IsElevated, checks if the script runs with elevated (administrator) privileges, which is crucial when altering user credentials.
  • Process Block: This is the heart of the script.
  • It first checks if the script has elevated rights, stopping execution if not.
  • Depending on the PowerShell version, it uses different methods to change the password:
  • For PowerShell version 2 or lower, it uses the net.exe command.
  • For later versions, the Set-LocalUser cmdlet changes the password.
  • End Block: Any residual password data in the $Password variable is cleared, ensuring no sensitive information lingers.

Potential Use Cases

Imagine an IT professional, John, in a mid-sized company. They recently faced a security breach and need to change the local administrator passwords across all systems as a preventive measure. John can deploy this script, ensuring all computers get their admin passwords reset efficiently, saving time and reducing human error.

Comparisons

Traditional methods of changing passwords often involve manually accessing each system or using native commands like net user. However, this script offers a more streamlined and automated approach, leveraging the capabilities of PowerShell. It’s more efficient, especially for batch operations across multiple machines.

FAQs

  • Can the script change passwords for non-admin users?
    Yes, specify a different username using the -UserName parameter.
  • What if I run the script without administrator privileges?
    The script will halt and prompt an “Access Denied” message.

Implications

Using scripts like this streamlines administrative tasks. However, automating password changes, if not done securely, might expose new passwords. Always ensure the transmission and storage of such scripts follow best security practices.

Recommendations

  • Always run such scripts in a secure environment.
  • Avoid hardcoding passwords within scripts. Instead, consider passing them as arguments or using secure credential managers.
  • Regularly update scripts to cater to the latest OS versions and PowerShell iterations.

Final Thoughts

Tools like NinjaOne amplify the power of scripts like this. Integrating automated scripts within platforms like NinjaOne ensures a smooth, error-free process, allowing IT professionals to focus on more pressing tasks. The combination of effective scripting with robust management platforms paves the way for a secure and efficient IT infrastructure.

 

Next Steps

Building an efficient and effective IT team requires a centralized solution that acts as your core service deliver tool. NinjaOne enables IT teams to monitor, manage, secure, and support all their devices, wherever they are, without the need for complex on-premises infrastructure.

Learn more about NinjaOne Remote Script Deployment, check out a live tour, or start your free trial of the NinjaOne platform.

Categories:

You might also like

Watch Demo×
×

See NinjaOne in action!

By submitting this form, I accept NinjaOne's privacy policy.

NinjaOne Terms & Conditions

By clicking the “I Accept” button below, you indicate your acceptance of the following legal terms as well as our Terms of Use:

  • Ownership Rights: NinjaOne owns and will continue to own all right, title, and interest in and to the script (including the copyright). NinjaOne is giving you a limited license to use the script in accordance with these legal terms.
  • Use Limitation: You may only use the script for your legitimate personal or internal business purposes, and you may not share the script with another party.
  • Republication Prohibition: Under no circumstances are you permitted to re-publish the script in any script library belonging to or under the control of any other software provider.
  • Warranty Disclaimer: The script is provided “as is” and “as available”, without warranty of any kind. NinjaOne makes no promise or guarantee that the script will be free from defects or that it will meet your specific needs or expectations.
  • Assumption of Risk: Your use of the script is at your own risk. You acknowledge that there are certain inherent risks in using the script, and you understand and assume each of those risks.
  • Waiver and Release: You will not hold NinjaOne responsible for any adverse or unintended consequences resulting from your use of the script, and you waive any legal or equitable rights or remedies you may have against NinjaOne relating to your use of the script.
  • EULA: If you are a NinjaOne customer, your use of the script is subject to the End User License Agreement applicable to you (EULA).