Computer >> 컴퓨터 >  >> 체계 >> Windows Server

PowerShell Invoke-Command를 사용하여 원격 컴퓨터에서 스크립트 실행

이 기사에서는 Invoke-Command를 사용하는 방법을 배웁니다. cmdlet을 사용하여 원격으로 PowerShell 명령 또는 스크립트를 실행합니다. PowerShell을 사용하여 네트워크에 있는 하나 이상의 컴퓨터에서 원격으로 명령을 실행할 수 있습니다. Invoke-Command cmdlet은 PowerShell Remoting의 원격 관리 기능을 사용하고 있습니다. . PowerShell Remoting을 사용하면 WinRM을 통해 컴퓨터의 PowerShell 세션에 원격으로 연결할 수 있습니다. (Windows 원격 관리) 서비스 및 관리용 웹 서비스 (WS-관리) 프로토콜. 이 서비스는 원격 PowerShell 세션을 설정하고 코드를 실행하는 기능을 제공합니다.

PowerShell Remoting용 WinRM 구성

PowerShell Remoting은 HTTP(포트 TCP/5985) 또는 HTTPS(포트 TCP/5986)를 사용하여 컴퓨터 간에 통신합니다. 기본적으로 HTTP 프로토콜이 사용되지만 이 트래픽도 AES-56을 사용하여 암호화됩니다(단, 중간자 공격의 위협이 있습니다). Kerberos 또는 NTLM 인증도 사용할 수 있습니다.

연결하려는 원격 컴퓨터에서 WinRM이 실행되고 있어야 합니다. WinRM 서비스 상태 확인:

Get-Service -Name "*WinRM*" | fl

서비스가 실행되고 있지 않으면 시작하십시오:

Enable-PSRemoting

WinRM has been updated to receive requests.
WinRM service started.
WinRM is already set up for remote management on this computer.

PowerShell Invoke-Command를 사용하여 원격 컴퓨터에서 스크립트 실행

이 명령은 WinRM 서비스를 시작하고(자동으로 시작하도록 설정), 기본 winrm 설정을 지정하고, Windows 방화벽에 예외 규칙을 추가합니다. Enable-PSRemoting –Force 명령은 사용자에게 메시지를 표시하지 않고 WinRM을 활성화합니다.

그런 다음 PowerShell Remoting을 사용하여 원격으로 컴퓨터에 연결할 수 있습니다.

네트워크 유형이 공개로 설정된 경우 PowerShell Remoting은 기본적으로 작동하지 않습니다. . 그런 다음 명령은 다음 오류를 반환합니다.

Set-WSManQuickConfig : ... WinRM firewall exception will not work since one of the network connection types on this machine is set to Public. Change the network connection type to either Domain or Private and try again.

네트워크 위치를 개인으로 변경하거나 다음 명령을 사용해야 합니다.

Enable-PSRemoting –SkipNetworkProfileCheck.

또한 공용 네트워크에서 WinRM에 대한 액세스를 허용하는 Windows Defender 방화벽 규칙을 사용하도록 설정합니다. GPO 또는 PowerShell을 사용하여 방화벽 규칙을 활성화할 수 있습니다.

Set-NetFirewallRule -Name 'WINRM-HTTP-In-TCP' -RemoteAddress Any

PowerShell Remoting을 통해 원격 컴퓨터에 대한 연결을 테스트하려면 다음 명령을 실행하십시오.

Test-WsMan compname1

PowerShell Invoke-Command를 사용하여 원격 컴퓨터에서 스크립트 실행

Active Directory 도메인이 없거나 IP 주소로 PowerShell Remoting을 통해 컴퓨터에 액세스하는 경우 이 경우 NTLM 프로토콜이 인증에 사용됩니다. NTLM을 사용할 때 Invoke-Command를 실행하려고 하면 다음 오류가 나타납니다.

[192.168.1.201] Connecting to remote server 192.168.1.102 failed with the following error message: The WinRM client cannot process the request. Default authentication may be used with an IP address under the following conditions: thetransport is HTTPS or the destination is in the TrustedHosts list, and explicit credentials are provided. Use winrm.cmd to configure TrustedHosts. Note that computers in the TrustedHosts list might not be authenticated. + FullyQualifiedErrorId: CannotUseIPAddress,PSSessionStateBroken

PowerShell Invoke-Command를 사용하여 원격 컴퓨터에서 스크립트 실행

연결에 사용하는 컴퓨터에서 NTLM 인증이 올바르게 작동하도록 하려면 WinRM용 SSL 인증서를 발급하거나 신뢰할 수 있는 호스트 목록에 호스트 이름/IP 주소를 추가하십시오.

Set-Item wsman:\localhost\Client\TrustedHosts -value 192.168.1.201

PowerShell Invoke-Command를 사용하여 원격 컴퓨터에서 스크립트 실행

또는 모든 컴퓨터에 연결을 허용할 수 있습니다(NTLM의 단점 중 하나이므로 권장하지 않습니다. 상호 인증을 지원하지 않습니다).

Set-Item wsman:\localhost\Client\TrustedHosts -value *

원격 호스트에 동일한 설정을 적용해야 합니다.

신뢰할 수 있는 호스트 목록을 표시하려면 다음 명령을 실행하십시오.

Get-Item WSMan:\localhost\Client\TrustedHosts

변경 사항을 적용하려면 WinRM을 다시 시작하십시오.

Restart-Service WinRM

그룹 정책을 사용하여 WinRM을 활성화하고 구성할 수도 있습니다.

Invoke-Command를 사용하여 원격으로 PowerShell 명령을 실행하는 방법

Invoke-Command cmdlet을 사용하면 하나 이상의 원격 컴퓨터에서 명령을 실행할 수 있습니다.

예를 들어 원격 컴퓨터에서 단일 명령을 실행하려면 다음을 사용하십시오.

Invoke-Command -ComputerName dc01 -ScriptBlock {$PSVersionTable.PSVersion}

PowerShell Invoke-Command를 사용하여 원격 컴퓨터에서 스크립트 실행

이 명령은 -ComputerName에 지정된 이름인 원격 컴퓨터에 설치된 PowerShell 버전을 표시합니다. 매개변수. -ScriptBlock {[cmdlet]}에 원격 컴퓨터에서 실행할 명령을 입력합니다. 차단합니다.

기본적으로 Invoke-Command를 통해 전송된 명령은 원격 컴퓨터에서 현재 사용자로 실행됩니다. 다른 사용자로 실행하려면 사용자 자격 증명을 요청하고 변수에 저장합니다.

$cred = Get-Credential
Invoke-Command -ComputerName dc01 -Credential $cred -ScriptBlock {Get-NetAdapter}

이 PowerShell 명령은 원격 컴퓨터의 네트워크 인터페이스 목록을 표시합니다.

PowerShell Invoke-Command를 사용하여 원격 컴퓨터에서 스크립트 실행

ScriptBlock에는 세미콜론으로 구분하여 둘 이상의 명령을 입력할 수 있습니다. 예를 들어 다음 명령은 현재 시간대를 표시하고 다른 시간대로 변경합니다.

Invoke-Command -Computername dc01 -ScriptBlock {Get-TimeZone| select DisplayName;Set-TimeZone -Name "Central Europe Standard Time”}

PowerShell Invoke-Command를 사용하여 원격 컴퓨터에서 스크립트 실행

Invoke-Command를 사용하면 개별 명령을 실행할 수 있을 뿐만 아니라 PowerShell 스크립트도 실행할 수 있습니다. 이를 위해 -ScriptBlock 대신 -FilePath 인수가 사용됩니다. 이 경우 컴퓨터에 있는 로컬 PS1 스크립트 파일의 경로를 지정합니다(스크립트 파일을 대상 원격 컴퓨터에 복사할 필요 없음):

Invoke-Command -ComputerName DC01 -FilePath C:\PS\Scripts\CheckSMBversion.ps1

Invoke-Command를 사용하여 여러 컴퓨터에서 동시에 명령을 실행하는 방법

Invoke-Command를 사용하여 여러 원격 컴퓨터에서 병렬로(동시에) 명령을 실행할 수 있습니다.

가장 간단한 경우 PowerShell 명령을 실행할 컴퓨터의 이름은 쉼표로 구분됩니다.

Invoke-Command server1, server2, server3 -ScriptBlock {get-date}

PowerShell Invoke-Command를 사용하여 원격 컴퓨터에서 스크립트 실행

컴퓨터 목록을 변수(배열)에 넣을 수 있습니다.

$servers = @("server1","server2","server3")
Invoke-Command -ScriptBlock { get-date} -ComputerName $servers

또는 텍스트 파일에서 가져오기:

Invoke-Command -ScriptBlock {Restart-Service spooler} -ComputerName(Get-Content c:\ps\servers.txt)

PowerShell 모듈용 AD에서 Get-ADComputer cmdlet을 사용하여 AD의 컴퓨터 목록을 가져올 수도 있습니다.

도메인의 모든 Windows Server 호스트에서 명령을 실행하려면 다음 PowerShell 코드를 사용하십시오.

$computers = (Get-ADComputer -Filter 'OperatingSystem -like "*Windows server*" -and Enabled -eq "true"').Name
Invoke-Command -ComputerName $computers -ScriptBlock {Get-Date} -ErrorAction SilentlyContinue

컴퓨터가 꺼져 있거나 사용할 수 없는 경우 스크립트는 SilentlyContinue 매개변수로 인해 중지되지 않고 다른 컴퓨터에서 계속 실행됩니다.

결과가 나온 컴퓨터를 이해하려면 PSComputerNamee 환경 변수를 사용하십시오.

$results = Invoke-Command server1, server2, server3 -ScriptBlock {get-date}
$results | Select-Object PSComputerName, DateTime

PowerShell Invoke-Command를 사용하여 원격 컴퓨터에서 스크립트 실행

여러 컴퓨터에서 Invoke-Command를 사용하여 명령을 실행할 때 동시에 실행됩니다. Invoke-Command에는 동시에 관리할 수 있는 최대 컴퓨터 수에 대한 제한이 있습니다(동시 PSSession의 제한된 수). 이 제한은 ThrottleLimit에서 설정됩니다. 매개변수(기본값은 32). 32대 이상의 컴퓨터(예:128대)에서 명령을 실행하려면 –ThrottleLimit 128을 사용하세요. (그러나 많은 수의 PSSession을 설정하려면 컴퓨터의 로드가 더 높아집니다.)

백그라운드에서 Invoke-Command를 통해 원격 컴퓨터에서 명령을 실행하려면 특수 속성 –AsJob 사용. 그러면 명령의 결과가 콘솔에 반환되지 않습니다. 결과를 얻으려면 Receive-Job을 사용하세요. cmdlet.