수색…


비고

PowerShell Remoting 활성화

원격으로 연결하려는 서버에서 먼저 PowerShell 원격 기능을 사용하도록 설정해야합니다.

Enable-PSRemoting -Force

이 명령은 다음을 수행합니다.

  • 다음 작업을 수행하는 Set-WSManQuickConfig cmdlet를 실행합니다.
  • WinRM 서비스를 시작합니다.
  • WinRM 서비스의 시작 유형을 자동으로 설정합니다.
  • 임의의 IP 주소 (존재하지 않는 경우)로 요구를 받아들이도록 (듯이) 청취자를 작성합니다.
  • WS-Management 통신에 대한 방화벽 예외를 사용합니다.
  • Microsoft.PowerShell 및 Microsoft.PowerShell.Workflow 세션 구성을 아직 등록하지 않은 경우이를 등록합니다.
  • 64 비트 컴퓨터에 Microsoft.PowerShell32 세션 구성이 등록되어 있지 않으면 등록합니다.
  • 모든 세션 구성을 사용합니다.
  • 원격 액세스를 허용하도록 모든 세션 구성의 보안 설명자를 변경합니다.
  • WinRM 서비스를 다시 시작하여 앞의 변경 사항을 적용합니다.

도메인 환경이 아닌 경우에만

AD 도메인의 서버의 경우 PS 원격 인증은 Kerberos ( 'Default') 또는 NTLM ( 'Negotiate')을 통해 수행됩니다. 비 도메인 서버에 원격 액세스를 허용하려면 두 가지 옵션이 있습니다.

인증서 생성을 필요로하는 HTTPS를 통한 WSMan 통신을 설정하거나 base64 인코딩 된 전신을 통해 자격 증명을 보내는 기본 인증을 사용합니다 (기본적으로 일반 텍스트와 동일하므로이 점에주의하십시오).

두 경우 모두 WSMan 신뢰할 수있는 호스트 목록에 원격 시스템을 추가해야합니다.

기본 인증 사용

Set-Item WSMan:\localhost\Service\AllowUnencrypted $true  

그런 다음에서 연결하고자하는 컴퓨터에, 당신은 당신이에 연결하는 컴퓨터를 신뢰하도록 지시해야합니다.

Set-Item WSMan:\localhost\Client\TrustedHosts '192.168.1.1,192.168.1.2'
Set-Item WSMan:\localhost\Client\TrustedHosts *.contoso.com
Set-Item WSMan:\localhost\Client\TrustedHosts *

중요 : 연결하려는 방식으로 주소가 지정된 컴퓨터를 신뢰하도록 클라이언트에 알려야합니다 (예 : IP를 통해 연결하는 경우 호스트 이름이 아닌 IP를 신뢰해야 함)

PowerShell을 통해 원격 서버에 연결

로컬 컴퓨터의 자격 증명 사용 :

Enter-PSSession 192.168.1.1

원격 컴퓨터에서 자격 증명 확인

Enter-PSSession 192.168.1.1 -Credential $(Get-Credential)

원격 컴퓨터에서 명령 실행

Powershell 원격 활성화 (Enable-PSRemoting) 원격 컴퓨터에서 다음과 같이 명령을 실행할 수 있습니다.

Invoke-Command -ComputerName "RemoteComputerName" -ScriptBlock {
    Write host "Remote Computer Name: $ENV:ComputerName"
}

위의 메서드는 임시 세션을 만들고 명령 또는 스크립트 블록이 끝난 직후에이를 닫습니다.

세션을 열린 상태로두고 나중에 다른 명령을 실행하려면 먼저 원격 세션을 만들어야합니다.

$Session = New-PSSession -ComputerName "RemoteComputerName"

그런 다음 원격 컴퓨터에서 명령을 호출 할 때마다이 세션을 사용할 수 있습니다.

Invoke-Command -Session $Session -ScriptBlock {
    Write host "Remote Computer Name: $ENV:ComputerName"
}

Invoke-Command -Session $Session -ScriptBlock {
    Get-Date
}

다른 자격 증명을 사용해야하는 경우, -Credential 매개 변수를 사용하여 -Credential 추가 할 수 있습니다.

$Cred = Get-Credential
Invoke-Command -Session $Session -Credential $Cred -ScriptBlock {...}

원격 직렬화 경고

노트 :

리모팅은 원격 시스템에서 PowerShell 개체를 직렬화하고 원격 세션이 끝날 때이를 deserialize합니다. 즉, 전송 중에 XML로 변환되어 모든 메서드가 손실됩니다.

$output = Invoke-Command -Session $Session -ScriptBlock {
    Get-WmiObject -Class win32_printer
}

$output | Get-Member -MemberType Method

  TypeName: Deserialized.System.Management.ManagementObject#root\cimv2\Win32_Printer

Name     MemberType Definition
----     ---------- ----------
GetType  Method     type GetType()
ToString Method     string ToString(), string ToString(string format, System.IFormatProvi...

일반 PS 객체에 대한 메서드가있는 반면 :

Get-WmiObject -Class win32_printer | Get-Member -MemberType Method

 TypeName: System.Management.ManagementObject#root\cimv2\Win32_Printer

Name                  MemberType Definition                                                                                                                          
----                  ---------- ----------                                                                                                                          
CancelAllJobs         Method     System.Management.ManagementBaseObject CancelAllJobs()                                                                              
GetSecurityDescriptor Method     System.Management.ManagementBaseObject GetSecurityDescriptor()                                                                      
Pause                 Method     System.Management.ManagementBaseObject Pause()                                                                                      
PrintTestPage         Method     System.Management.ManagementBaseObject PrintTestPage()                                                                              
RenamePrinter         Method     System.Management.ManagementBaseObject RenamePrinter(System.String NewPrinterName)                                                  
Reset                 Method     System.Management.ManagementBaseObject Reset()                                                                                      
Resume                Method     System.Management.ManagementBaseObject Resume()                                                                                     
SetDefaultPrinter     Method     System.Management.ManagementBaseObject SetDefaultPrinter()                                                                          
SetPowerState         Method     System.Management.ManagementBaseObject SetPowerState(System.UInt16 PowerState, System.String Time)                                  
SetSecurityDescriptor Method     System.Management.ManagementBaseObject SetSecurityDescriptor(System.Management.ManagementObject#Win32_SecurityDescriptor Descriptor)

인수 사용법

원격 스크립팅 블록의 매개 변수로 인수를 사용하려면 Invoke-CommandArgumentList 매개 변수를 사용하거나 $Using: 구문을 $Using: 합니다.

명명되지 않은 매개 변수가있는 ArgumentList 사용 (즉, 스크립트 블록에 전달 된 순서대로) :

$servicesToShow = "service1"
$fileName = "C:\temp\servicestatus.csv"
Invoke-Command -Session $session -ArgumentList $servicesToShow,$fileName -ScriptBlock {
    Write-Host "Calling script block remotely with $($Args.Count)"
    Get-Service -Name $args[0]
    Remove-Item -Path $args[1] -ErrorAction SilentlyContinue -Force
}

명명 된 매개 변수와 함께 ArgumentList 사용 :

$servicesToShow = "service1"
$fileName = "C:\temp\servicestatus.csv"
Invoke-Command -Session $session -ArgumentList $servicesToShow,$fileName -ScriptBlock {
    Param($serviceToShowInRemoteSession,$fileToDelete)

    Write-Host "Calling script block remotely with $($Args.Count)"
    Get-Service -Name $serviceToShowInRemoteSession
    Remove-Item -Path $fileToDelete -ErrorAction SilentlyContinue -Force
}

$Using: 구문 $Using: :

$servicesToShow = "service1"
$fileName = "C:\temp\servicestatus.csv"
Invoke-Command -Session $session -ScriptBlock {
    Get-Service $Using:servicesToShow
    Remove-Item -Path $fileName -ErrorAction SilentlyContinue -Force
}

PSSession을 자동으로 정리하는 가장 좋은 방법

New-PSsession cmdlet을 통해 원격 세션을 New-PSsession 현재 PowerShell 세션이 끝날 때까지 PSSession이 유지됩니다. 기본적으로 PSSession 및 모든 관련 리소스는 현재 PowerShell 세션이 끝날 때까지 계속 사용됩니다.

여러 개의 활성 PSSessions 은 특히 ​​PowerShell 세션 하나에서 수백 개의 PSSessions 을 만드는 장시간 실행되거나 연결된 스크립트의 경우 리소스에 부담이 될 수 있습니다.

PSSession 이 사용 된 후에 명시 적으로 제거하는 것이 가장 좋습니다. [1]

다음 코드 템플릿은 위의 작업을 수행하기 위해 try-catch-finally 를 사용합니다. 오류 처리를 안전한 방법으로 결합하여 사용 된 모든 생성 된 PSSessions 이 제거 된 것을 확인합니다.

try
{
    $session = New-PSsession -Computername "RemoteMachineName"
    Invoke-Command -Session $session -ScriptBlock {write-host "This is running on $ENV:ComputerName"}
}
catch
{
    Write-Output "ERROR: $_"
}
finally
{
    if ($session)
    {
        Remove-PSSession $session
    }
}

참고 자료 : [1] https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/new-pssession



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow