Tìm kiếm trang web

Đặt tài khoản người dùng cục bộ bằng PowerShell


Trước tiên, hãy để tôi chỉ ra rằng việc quản lý tài khoản người dùng cục bộ trên máy tính từ xa bằng PowerShell thực sự khá dễ dàng. Tất cả những gì bạn cần làm là tìm hiểu cách sử dụng lệnh NET USER và thực thi nó bằng Invoke-Command.

invoke-command { net user } -computername chi-core01

invoke-command { net user localadmin } -computername chi-core01

Tài khoản LocalAdmin trên CHI-CORE01 hiện đã bị vô hiệu hóa (tài khoản hoạt động bằng không). Nhưng việc kích hoạt và đặt mật khẩu mới khá dễ dàng.

invoke-command { net user localadmin P@ssw0rd /active:Yes } -computername chi-core01

Tuy nhiên, điều này không có quy mô tốt và khả năng của lệnh NET USER có thể khác nhau tùy theo hệ điều hành. Vì vậy, đây là hàm PowerShell sử dụng ADSI để thực hiện điều tương tự.

#requires -version 2.0

Function Set-LocalUserAccount {
<#
.SYNOPSIS
Enable or disable a local user account.

.DESCRIPTION
This command will allow you to set the password of a local user account as well
as enable or disable it. By default, this command will not write anything to
the pipeline unless you use -Passthru.  You must run this under credentials 
that have administrator rights on the remote computer.

.PARAMETER ComputerName 
The name of the computer to connect to. This parameter has an alias of CN.
.PARAMETER UserName 
The name of the local user account on the computer.
.PARAMETER Password 
The new password to set. This parameter has an alias of PWD.
.PARAMETER Status 
Enable or disable the local user account.
.PARAMETER Passthru
Write the user account object to the pipeline
.EXAMPLE
PS C:\> Set-LocalUserAccount SERVER01,SERVER02 DBAdmin -status disable

Disable the local user account DBAdmin on SERVER01 and SERVER02

.EXAMPLE
PS C:\> get-content c:\work\computers.txt | set-localuseraccount LocalAdmin -password "^Crx33t7A"

Sets the password for account LocalAdmin on all computers in computers.txt

.NOTES
Version: 1.0
Author : Jeff Hicks (@JeffHicks)

Learn more:
 PowerShell in Depth: An Administrator's Guide (http://www.manning.com/jones2/)
 PowerShell Deep Dives (http://manning.com/hicks/)
 Learn PowerShell 3 in a Month of Lunches (http://manning.com/jones3/)
 Learn PowerShell Toolmaking in a Month of Lunches (http://manning.com/jones4/)


  ****************************************************************
  * DO NOT USE IN A PRODUCTION ENVIRONMENT UNTIL YOU HAVE TESTED *
  * THOROUGHLY IN A LAB ENVIRONMENT. USE AT YOUR OWN RISK.  IF   *
  * YOU DO NOT UNDERSTAND WHAT THIS SCRIPT DOES OR HOW IT WORKS, *
  * DO NOT USE IT OUTSIDE OF A SECURE, TEST SETTING.             *
  ****************************************************************

.INPUTS
String
.OUTPUTS
None or System.DirectoryServices.DirectoryEntry

#>

[cmdletbinding(SupportsShouldProcess=$True)]

Param (
[Parameter(Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[ValidateNotNullorEmpty()]
[Alias("cn")]
[string[]]$ComputerName=$env:COMPUTERNAME, 
[Parameter(Position=1,Mandatory=$True,
HelpMessage="What is the name of the local user account?",
ValueFromPipelineByPropertyName=$True)]
[ValidateNotNullorEmpty()]
[string]$UserName, 
[Parameter(ValueFromPipelineByPropertyName=$True)]
[Alias("pwd")]
[string]$Password, 
[ValidateSet("Enable","Disable")]
[string]$Status="Enable",
[switch]$Passthru
)

Begin {
    Write-Verbose "Starting $($myinvocation.mycommand)"
    #define a constant to disable or enable an account
    New-Variable ADS_UF_ACCOUNTDISABLE 0x0002 -Option Constant

    Write-Verbose "Setting local user account $username"
} #begin

Process {
    foreach ($computer in $computername) {
        Write-Verbose "Connecting to $computer"
        Write-Verbose "Getting user account"

        $Account = [ADSI]"WinNT://$computer/$username,user"

        #validate the user account was found
        if (-NOT $Account.path) {
            Write-Warning "Failed to find $username on $computername"
            #bail out
            Return
        }

        #Get current enabled/disabled status
        if ($Account.userflags.value -band $ADS_UF_ACCOUNTDISABLE) {
          $Enabled = $False
        }
        else {
          $Enabled = $True
        }

        Write-verbose "Account enabled is $Enabled"

        if ($enabled -AND ($Status -eq "Disable")) {
            Write-Verbose "disabling the account"
            $value=$Account.userflags.value -bor $ADS_UF_ACCOUNTDISABLE
            $Account.put("userflags",$value)
        }
        elseif ((-NOT $enabled) -AND ($Status -eq "Enable")) {
            Write-Verbose "Enabling the account"
            $value=$Account.userflags.value -bxor $ADS_UF_ACCOUNTDISABLE
            $Account.put("userflags",$value)
        }
        else {
            #account is already in the desired state
            Write-Verbose "No change necessary"
        }

        if ($Password) {
            Write-Verbose "Setting acccount password"
            $Account.SetPassword($Password)
        }
    
        #Whatif
        if ($PSCmdlet.ShouldProcess("$computer\$username")) {
            Write-Verbose "Committing changes"
            $Account.SetInfo()
         }
         if ($Passthru) {
            Write-Verbose "Passing object to the pipeline"
            $Account

         }
    } #foreach
} #process

End {    
    Write-Verbose "Ending $($myinvocation.mycommand)"
} #end
 
} #end Set-LocalUserAccount function

Chức năng này sẽ hoạt động trong PowerShell 2.0 trở lên. Nội dung trợ giúp bao gồm một số ví dụ sử dụng. Bạn có thể sử dụng lệnh này để thay đổi mật khẩu người dùng hoặc thay đổi mật khẩu trong khi bật hoặc tắt tài khoản. Việc bật và tắt được thực hiện bằng thao tác theo bit với giá trị cờ người dùng và cờ không đổi cho biết tài khoản đã bị vô hiệu hóa.

Có lẽ có nhiều thứ khác có thể được thêm vào lệnh chẳng hạn như đặt thuộc tính nhận xét và khi tài khoản hết hạn. Nhưng bây giờ tôi sẽ để lại những thay đổi đó cho bạn.

Bài viết liên quan