PowerShell Script for Local Admin

Securing Windows Systems with Intune: Deploying PowerShell Script for Automated Local Admin Account Management

I have a situation to create a local administrator account with Microsoft Intune powershell script and deploy it to Windows Devices.

Key Features:

  1. Create a local account
  2. Add account to Local administrators Group
  3. Set password to never expire and can;t change

Deploy from Intune as Powershell script Ready to Deploy? Download the below script.

####################################################
# Script: Create-Local-admin-account.ps1
# Scope: Creates new local admin account and adds it to the Administrators group, Sets password never Expire and can;t change Password
####################################################

$Username = "Local-Admin"
$Password = "LocalAdmin&123"
$group = "Administrators"

$adsidetails = [ADSI]"WinNT://$env:COMPUTERNAME"
$usercheck = $adsidetails.Children | Where-Object { $_.SchemaClassName -eq 'user' -and $_.Name -eq $Username }

if ($usercheck -eq $null) {
    try {
        # Create a new local user
        & NET USER $Username $Password /add /y /expires:never /passwordchg:no

        # Add the local user to the Administrators group
        & NET LOCALGROUP $group $Username /add

        Write-Host "Successfully created and added $($Username) to $($group)."
    }
    catch {
        Write-Host "Error creating or adding $($Username): $_"
        exit 1 # Exit with an error code
    }
} else {
    try {
        # Set the password for an existing local user
        $usercheck.SetPassword($Password)

        Write-Host "Successfully set the password for existing local user $($Username)."
    }
    catch {
        Write-Host "Error setting the password for $($Username): $_"
        exit 1 # Exit with an error code
    }
}

try {
    # Set the password for $Username to never expire using Set-LocalUser
    Set-LocalUser -Name $Username -PasswordNeverExpires $true

    Write-Host "Successfully set the password for $($Username) to never expire."
}
catch {
    Write-Host "Error setting password to never expire for $($Username): $_"
    exit 1 # Exit with an error code
}

Leave a Comment