Powershell – Can’t find Microsoft.Powershell.LocalAccounts module (or run Get-LocalUser)

modulepowershellwindows-server-2008-r2

When running a script, I have a line to verify that a "service account" (aka a local user account) for our app exists:

$svcAccountName = "TheAccountName"
$svcAccount = Get-LocalUser -Name $svcAccountName

The server (Windows Server 2008 R2) is balking at the Get-LocalUser cmdlet, stating:

Get-LocalUser : The term 'Get-LocalUser' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ Get-LocalUser 
+ ~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Get-LocalUser:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

So I tried to import the LocalAccounts module:

Import-Module Microsoft.Powershell.LocalAccounts

and I got this:

Import-Module : The specified module 'LocalAccounts' was not loaded because no
valid module file was found in any module directory.
At line:1 char:1
+ Import-Module
+ ~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (LocalAccounts:String)[Import-Module], FileNotFoundException
    + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand

The server is running PSVersion 4.0 according to the $PSVersionTable variable.

Why isn't the LocalAccounts module loaded and the Get-LocalUser command running?
How can I fix this?

Best Answer

Beginning with Windows 10 including Server 2016 and 2019, the Windows Management Framework (which includes the local account management Powershell module) is now shipped "in-box". See https://docs.microsoft.com/en-us/powershell/wmf/overview#wmf-availability-across-windows-operating-systems for information about WMF for other versions of Windows.

This means that functions like Get-LocalUser and New-LocalUser are available without having to install or import any modules.

Note that parameter names have changed for many of these functions from WMF 5.1. Additionally, the password must now be supplied as a secure string which may be generated using the ConvertTo-SecureString function.

Here's an example to check for an existing user and create the user if they don't exit:

$UserName = "AdaLovelace"
$SecurePassword = ConvertTo-SecureString "ThisIsAPassword!" –asplaintext –force
if (Get-LocalUser($UserName))
{
    Echo "User exists"
}
else
{
    New-LocalUser $UserName -Password $SecurePassword -UserMayNotChangePassword -AccountNeverExpires
}
Related Topic