cel09
cel09

Reputation: 63

Check if local user is enabled or disabled

I need a seemingly simple if code that would check if a local user is enabled or disabled.

After check has been made I need to disable a user which is simple (Disable-LocalUser -Name "User"), however I cannot work out a part that would first check if a user is in enabled state.

Thank you.

Upvotes: 1

Views: 13998

Answers (2)

Sid
Sid

Reputation: 2676

Assuming you have the name of the user in $user

if ((Get-LocalUser -Name $user).Enabled)
{
    <#disable code here#>
}

This should work.

EDIT Detailed:

$User = "blahblah"
try
{
    $Result = (Get-LocalUser -Name $user -ErrorAction Stop).Enabled
    try
    {
        if ($Result)
        {
            "disable code here"
        }
    }
    catch
    {
        $_.Exception.Message #in case disable fails
    }
}
catch
{
    $_.Exception.Message #if user doesnt exist
}

Upvotes: 3

user6811411
user6811411

Reputation:

You could check Enabled state with a Where-Object and directly pipe to Disable-LocalUser provided the script runs elevated.

PoSh> Get-LocalUser -Name TestUser | Where-Object Enabled

Name     Enabled Description
----     ------- -----------
TestUser True    UserTest


PoSh> Get-LocalUser -Name TestUser | Where-Object Enabled | Disable-LocalUser
PoSh> Get-LocalUser -Name TestUser

Name     Enabled Description
----     ------- -----------
TestUser False   UserTest

Upvotes: 0

Related Questions