PowerShell 遠端執行:像專家一樣執行遠端命令

假設你已經學會了在本地執行命令;這已經是掌握遠程執行的一個踏腳石。PowerShell 遠程執行允許管理員在遠程系統上執行命令和腳本。

本指南演示了在 Active Directory (AD) 環境中設置和使用 PowerShell 遠程執行。想像一下,在不離開辦公桌的情況下,遠程創建文件、運行腳本或檢查配置。

設置和使用 PowerShell 遠程執行,讓你自信地在遠程系統上執行腳本!

為標準用戶設置 PowerShell 遠程執行

在充分利用 PowerShell 遠程執行之前,必須確保必要的權限已到位。遠程運行命令或腳本依賴於適當的配置,特別是在安全性優先的 Active Directory 環境中。

首先,嘗試使用 Invoke-Command 連接到遠程服務器 (SRV2)。以下命令在遠程計算機上運行一個腳本塊:

Invoke-Command -ComputerName SRV2 -ScriptBlock {Write-Host "Hi, I'm running code on the $(hostname) remote computer!"}

如果身份驗證失敗,通常意味著用戶缺乏必要的權限。

默認情況下,非管理用戶必須是遠程計算機本地 遠程管理用戶 群組的成員。

檢查群組成員資格:

Get-LocalGroupMember -Group 'Remote Management Users'

如果用戶不在列表中,請將他們添加:

Add-LocalGroupMember -Group 'Remote Management Users' -Member user
Get-LocalGroupMember -Group 'Remote Management Users'

現在,重試 Invoke-Command 命令以確認連接。

Invoke-Command -ComputerName SRV2 -ScriptBlock {Write-Host "Hi, I'm running code on the $(hostname) remote computer!"}

遠程運行基本腳本

一旦配置了 PowerShell Remoting,您就可以在遠端計算機上運行命令。這種功能可以解鎖自動化任務、收集數據和遠程疑難排解的潛力。

要了解 PowerShell Remoting 的工作原理,請在遠端計算機上創建一個文本文件,然後驗證操作是否成功。

定義並執行 scriptblock:

$scriptblock = { Set-Content -Path 'somefile.txt' -Value '' }
Invoke-Command -Scriptblock $scriptblock -ComputerName SRV2

使用以下命令驗證文件是否已創建:

此命令連接到遠端計算機 SRV2,檢索有關文件 somefile.txt 的信息,並僅輸出其名稱和創建時間。

icm -ComputerName SRV2 -ScriptBlock {Get-Item somefile.txt} | Select-Object Name, CreationTime

在遠端計算機上運行本地腳本

也許單個命令不夠用,您可能需要運行存儲在本機計算機上的完整腳本。如果是這樣,PowerShell Remoting 可讓您快速將本地腳本發送到遠端計算機並執行,就好像您親自在那裡一樣。

為展示在遠端計算機上運行腳本,請在本地創建一個簡短的腳本,然後在遠端計算機上運行以自動執行操作或清理任務。

使用此命令在本地創建一個腳本,其中:

  • $scriptContents 使用 here-string (@' ... '@) 將腳本存儲為多行字符串,這有助於使腳本易讀且組織有序。
  • Set-Content$scriptContents 的內容寫入到名為 *RunThisRemotely.ps1* 的文件中,保存在當前目錄中。
$scriptContents =
@'
Write-Host "Deleting the file just created..."
Remove-Item -Path somefile.txt
'@
Set-Content -Path 'RunThisRemotely.ps1' -Value $scriptContents

確認腳本內容:

Get-Content RunThisRemotely.ps1

遠程運行腳本:

Invoke-Command -ComputerName SRV2 -FilePath RunThisRemotely.ps1

現在,驗證測試文件是否已刪除:

icm -ComputerName SRV2 -ScriptBlock {Test-Path somefile.txt}

使用Scripblock驗證本地註冊表鍵

PowerShell Remoting支持在本地和遠程會話之間傳遞變量,從而實現靈活且可重用的腳本。但首先,讓我們專注於在本地檢查註冊表鍵。

存儲多個後續可以檢查其是否存在於系統中的註冊表路徑:

# Define an array of registry paths to check
$registryKeyPaths = @(
    'HKLM:\SOFTWARE\Microsoft\AppV\', 
    'HKLM:\SOFTWARE\Microsoft\AccountsControl\'
)

將此添加到腳本中以定義一個腳本塊 ****($localScriptBlock),該腳本塊在計算機上本地執行。 腳本塊檢查特定註冊表路徑是否存在於本地計算機上並為每個路徑提供反饋。

# Define the script block that will run locally on the computer
$localScriptBlock = {
    ## Iterate through each registry path in the $registryKeyPaths array
    foreach ($path in $registryKeyPaths) {
        # Check if the current registry path exists on the local machine
        if (Test-Path -Path $path) {
            # If the path exists, output a message confirming its existence
            Write-Host -Object "The registry path [$path] exists on the computer $(hostname)."
        } else {
            # If the path does not exist, output a message stating its absence
            Write-Host -Object "The registry path [$path] does not exist on the computer $(hostname)."
        }
    }
}

執行腳本塊並查看發生了什麼。

Invoke-Command -ScriptBlock $localScriptBlock

將本地變量傳遞到遠程會話

無論您是使用數組、字符串還是對象,您都可以通過兩種方式將數據傳遞給遠程命令:

  • $using–將本地變量直接集成到腳本塊中。
  • ArgumentList–明確將變量傳遞給腳本塊以供使用。

繼續閱讀以探索實現此目標的兩種方法($usingArgumentList)。

使用$using關鍵字(首選方法)

確認註冊表鍵存在後,下一步是在本地讀取該數組並在遠程計算機上使用。實現這一目標的一種方法是使用$using 關鍵字來引用遠程會話中的本地變量。

創建這個腳本在遠程計算機上運行並檢查指定的註冊表路徑。該腳本提供關於每個路徑是否存在的反饋。

使用這種方法,只需將$using 前綴添加到本地變量中。這個操作告訴 PowerShell 在執行代碼在遠程計算機之前引用本地變量registryKeyPaths

$remoteScriptBlock = {
    ## Check to see if the registry keys exist on the computer
    foreach ($path in $using:registryKeyPaths) {
        if (Test-Path -Path $path) {
            Write-Host -Object "The registry path [$path] exists on the computer $(hostname)."
        } else {
            Write-Host -Object "The registry path [$path] does not exist on the computer $(hostname)."
        }
    }
}

然後,您可以調用遠程命令在遠程計算機上執行代碼:

Invoke-Command -ScriptBlock $remoteScriptBlock -ComputerName SRV2

看起來註冊表鍵也存在那裡。

使用ArgumentList 參數

除了$using 關鍵字之外,另一個選項是使用ArgumentList 參數將變量發送到遠程會話。

創建一個腳本(類似於帶有$using 關鍵字的腳本),該腳本使用$args 數組來訪問通過ArgumentList 參數傳遞的值。

在這種方法中,您指定一個或多個要通過ArgumentList 參數發送到遠程會話的變量。在腳本塊內,用$args 替換本地變量,PowerShell 將自動填充通過ArgumentList 傳遞的值。

$remoteScriptBlock = {
    ## Check to see if the registry keys exist on the computer
    foreach ($path in $args) {
        if (Test-Path -Path $path) {
            Write-Host -Object "The registry path [$path] exists on the computer $(hostname)."
        } else {
            Write-Host -Object "The registry path [$path] does not exist on the computer $(hostname)."
        }
    }
}

現在,通過以下命令執行腳本:

Invoke-Command -ScriptBlock $remoteScriptBlock -ComputerName SRV2 -ArgumentList $registryKeyPaths

這兩種方法都會產生相同的輸出,確認遠端電腦上的註冊表鍵存在。

按照這些步驟,您可以有效地設置和使用 PowerShell 遙控來在遠端系統上運行命令和腳本。

結論

在本教程中,您學會了如何在 Active Directory 環境中設置 PowerShell 遙控,如何在遠端系統上運行命令和腳本,以及如何有效地傳遞變數。這些基本技能對於自動化管理任務和高效管理系統至關重要。

現在您已掌握了基礎知識,可以考慮探索更高級的主題。可以研究持久的 PowerShell 會話、處理遠端錯誤,或創建可重用的腳本以處理批量操作。

使用 PowerShell 遙控的可能性是無窮無盡的,因此開始實驗,讓您的工作流程更加高效吧!

Source:
https://adamtheautomator.com/powershell-remoting-guide/