簡體   English   中英

簡單的 Powershell 問題(創建本地 ID 並添加本地管理員組以及一些檢查)

[英]Simple Powershell questions (Creating a local ID and adding local administrator group plus some checks)

對 powershell 有點陌生,正在尋找一些指導。 我正在嘗試創建一個簡單的腳本來完成以下任務:

  1. 檢查服務器列表中是否已存在本地 ID
  2. 如果沒有,請創建一個並添加到服務器列表中的本地管理員組
  3. 登出結果
$serverlist = Get-Content C:\temp\servers.txt
$credential = Get-Credential
    foreach ($server in $serverlist){
    #User to search for
    $USERNAME = "John"

    #Declare LocalUser Object
    $ObjLocalUser = $null

    Invoke-Command -Credential $credential -Authentication Default -ComputerName $Server -ScriptBlock {
    $ObjLocalUser = Get-LocalUser "John"
    
    #Create the user if it was not found (Example)
    if (!$ObjLocalUser) {
    Write-Verbose "Creating User $($USERNAME)" #(Example)
    NET USER "John" "Generic Password" /ADD /passwordchg:no
    NET LOCALGROUP "Administrators" "Joe Doe" /ADD
        }

    else {
    Write-Verbose "John" already exists"
    }
  }
}

PS,為簡單起見僅使用通用憑據,之后將轉換為最佳標准。 只是想獲得更多編寫 Powershell 的經驗,以后可能會轉換為自定義 function。

根據您的腳本,我注意到以下幾點可以增強

1-您不必使用 for 循環遍歷服務器列表,而是可以將服務器列表數組直接傳遞給Invoke-CommandComputerName參數

get-help Invoke-Command

Invoke-Command [[-ComputerName] <string[]>] 
# <string[]: indicate that the computername property accepts an array not string
    

所以在你的腳本中你可以使用它如下

Invoke-Command -Credential $credential -Authentication Default -ComputerName $Serverlist {...}

2- 在Invoke-Command中,您使用命令搜索用戶是否存在

Get-LocalUser "John"

但是如果用戶不存在,這會給你一個錯誤

PS C:\Windows\system32> Get-LocalUser john

Get-LocalUser : User john was not found.
At line:1 char:1
+ Get-LocalUser john
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (john:String) [Get-LocalUser], UserNotFoundException
    + FullyQualifiedErrorId : UserNotFound,Microsoft.PowerShell.Commands.GetLocalUserCommand

而不是您可以使用以下方法搜索用戶:

Get-LocalUser | where {$_.name -eq $USERNAME})

3-您不需要使用變量$ObjLocalUser ,您可以使用 if 條件直接檢查搜索結果,如下所示:

if (!(Get-LocalUser | where {$_.name -eq $USERNAME})) {
        Write-output "Creating User $USERNAME" 
        
    } else {
        Write-output "User: $USERNAME already exists"
    }

最后:為了在invoke-commnd命令中使用局部變量,您可以使用Using scope 修飾符來識別遠程命令中的局部變量。

所以腳本可能是這樣的:

$serverlist = Get-Content C:\temp\servers.txt
$credential = Get-Credential
$USERNAME = "John"
Invoke-Command -Credential $credential -Authentication Default -ComputerName $serverlist -ScriptBlock {
    
    #Create the user if it was not found (Example)
    if (!(Get-LocalUser | where {$_.name -eq $Using:USERNAME})) {
        Write-output "Creating User $Using:USERNAME" 
        NET USER $Using:USERNAME "Generic Password" /ADD /passwordchg:no
        NET LOCALGROUP "Administrators" $Using:USERNAME /ADD
    } else {
        Write-output "User: $Using:USERNAME already exists"
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM