PowerShell 재사용 가능 세션: 지속적인 원격 연결 안내

원격 시스템을 관리하는 것은 여러 명령을 여러 시스템에 실행할 때 특히 머리아플 수 있습니다. 시스템에 다시 연결하는 반복적인 작업은 시간을 낭비하고 업무 효율을 떨어뜨릴 수 있습니다. 익숙한 상황인가요? 걱정하지 마세요, 더 좋은 방법이 있습니다!

이 안내서에서는 재사용 가능한 PowerShell 원격 세션을 사용하여 원격 시스템을 더 빠르고 쉽게 효율적으로 관리하는 방법을 배우게 됩니다.

PowerShell 원격 기술을 더 높은 수준으로 끌어올릴 준비가 되었나요? 시작해봅시다!

세션 생성 및 사용

원격 시스템 작업 시, 가장 지루한 작업 중 하나는 매번 명령을 실행할 때마다 다시 연결해야 하는 것입니다. 이러한 경우에 재사용 가능한 세션이 유용합니다.

지속적인 세션 생성은 지속적인 연결을 유지합니다. 이렇게 함으로써 여러 번 명령을 반복 실행할 때 연결 및 연결 해제가 필요 없어집니다.

먼저, 재사용 가능한 세션을 생성해야 합니다.

New-PSSession cmdlet은 원격 컴퓨터에 지속적인 연결을 설정합니다:

$session = New-PSSession -ComputerName SRV2

이 세션 객체는 Invoke-Command와 같은 명령에 전달하여 스크립트 전체에서 동일한 세션을 재사용할 수 있습니다.

예를 들어, 기본 명령을 실행하여 연결을 테스트할 수 있습니다:

Invoke-Command -Session $session -ScriptBlock { hostname }

재사용 가능한 세션을 사용하면 원격 시스템에 변수를 저장하고 검색할 수도 있습니다:

Invoke-Command -Session $session -ScriptBlock { $foo = 'Please be here next time' }
Invoke-Command -Session $session -ScriptBlock { $foo }

이 지속적인 저장 기능은 재사용 가능한 세션의 중요한 장점으로, 여러 명령을 통해 상태를 유지할 수 있게 해줍니다.

원격 사용을 위한 함수 수정

재사용 가능한 세션과 함께 작동하도록 인벤토리 기능을 조정해 보겠습니다.

먼저, 세션 객체를 수용하기 위해 Session 매개변수를 추가합니다. 여기서 Get-Member cmdlet은 세션 객체 유형을 식별하는 데 도움을 줍니다:

$session | Get-Member

세션 객체가 System.Management.Automation.Runspaces.PSSession 유형임을 확인한 후, 다음 단계는 Get-WmiObjectValue 함수를 정의하는 것입니다.

이 함수는 세션 매개변수를 사용하여 원격 실행을 가능하게 하여, 원격 시스템에서 스크립트 블록을 실행하고 특정 WMI 속성을 검색할 수 있게 합니다.

function Get-WmiObjectValue {
    [CmdletBinding()]
    param(
        # Specify the name of the WMI property to query
        [Parameter(Mandatory)]
        [string]$PropertyName,

        # Specify the name of the WMI class to query
        [Parameter(Mandatory)]
        [string]$WmiClassName,

        # Specify the remote session object to use for invoking the command
        [Parameter(Mandatory)]
        [System.Management.Automation.Runspaces.PSSession]$Session
    )

    # Define the script block to execute on the remote machine
    $scriptBlock = {
        # Get the sum of the specified property from the WMI class
        $number = (Get-CimInstance -ClassName $using:WmiClassName | Measure-Object -Property $using:PropertyName -Sum).Sum

        # Convert the sum to gigabytes
        $numberGb = $number / 1GB

        # Round the result to 2 decimal places
        [math]::Round($numberGb, 2)
    }

    # Execute the script block on the remote machine using the provided session
    Invoke-Command -Session $Session -Scriptblock $scriptBlock
}

이 함수를 사용해 보고 무슨 일이 일어나는지 살펴보겠습니다.

Get-WmiObjectValue -PropertyName Capacity -WmiClassName Win32_PhysicalMemory -Session $session

어느 시점에서 이 오류가 발생할 수 있습니다. 하지만 걱정하지 마세요. 계속 읽으면 이 오류를 해결하는 방법을 배울 수 있습니다.

인증 문제 해결하기

“액세스 거부” 오류가 발생하는 경우, 이는 권한이 부족하기 때문일 가능성이 높습니다. 기본적으로 재사용 가능한 세션은 생성할 때 사용된 자격 증명을 상속받습니다.

현재 인증된 사용자의 사용자 이름을 시스템에서 확인하세요:

whoami

도메인 사용자, 즉 사용자에게 원격 컴퓨터에서 WMI를 쿼리할 권한이 없다면, Invoke-Command를 사용하여 관리자 계정을 이용하도록 권한을 상승시켜야 합니다.

먼저, Get-Credential cmdlet을 사용하여 세션 생성 시 대체 자격 증명을 지정하는 자격 증명 객체를 만듭니다:

$adminCred = Get-Credential -UserName adam

인증이 완료되면, 세션을 테스트합니다:

Invoke-Command -Session $session -Scriptblock {hostname} -Credential $adminCred

이 테스트는 인벤토리 기능을 실행하기 전에 세션이 예상대로 작동하는지 확인합니다.

하지만 세션이 작동하지 않았다면 잘못된 자격 증명으로 이미 생성된 것입니다. 그렇다면 현재 세션을 제거해야 합니다:

Remove-PSSession -Session $session

Remove-PSSession cmdlet은 로컬 및 원격 컴퓨터 모두에서 세션을 제거합니다.

이전 세션이 제거되면 새로운 세션을 하나 더 생성합니다. 하지만 이번에는 관리 사용자로 인증된 세션을 생성합니다:

$session = New-PSSession -ComputerName SRV2 -Credential $adminCred

새 세션을 사용하여 Invoke-Command를 다시 시도하고 어떤 일이 발생하는지 확인하십시오.

Invoke-Command -Session $session -Scriptblock {hostname} -Credential $adminCred

이제 새 세션이 작동한다고 확신하므로 다시 함수를 시도해 보겠습니다.

Get-WmiObjectValue -PropertyName Capacity -WmiClassName Win32_PhysicalMemory -Session $session

모든 것을 통합하기

힘든 작업이 끝났고 이제 모든 것을 하나의 스크립트로 결합할 시간입니다.

이 최종 스크립트는 인벤토리 정보를 수집하고 결과를 표시하며 세션을 정리합니다:

function Get-WmiObjectValue {
    [CmdletBinding()]
    param(
        # Specify the name of the WMI property to query
        [Parameter(Mandatory)]
        [string]$PropertyName,

        # Specify the name of the WMI class to query
        [Parameter(Mandatory)]
        [string]$WmiClassName,

        # Specify the remote session object to use for invoking the command
        [Parameter(Mandatory)]
        [System.Management.Automation.Runspaces.PSSession]$Session
    )

    # Define the script block to execute on the remote machine
    $scriptBlock = {
        # Get the sum of the specified property from the WMI class
        $number = (Get-CimInstance -ClassName $using:WmiClassName | Measure-Object -Property $using:PropertyName -Sum).Sum

        # Convert the sum to gigabytes
        $numberGb = $number / 1GB

        # Round the result to 2 decimal places
        [math]::Round($numberGb, 2)
    }

    # Execute the script block on the remote machine using the provided session
    Invoke-Command -Session $Session -Scriptblock $scriptBlock
}

## Grab the alternate credential: Get-CimInstance will work on the remote computer
$adminCred = Get-Credential -UserName adam

## Create a session authenticating as the adam (admin) user
$session = New-PSSession -ComputerName SRV2 -Credential $adminCred

## Find the total memory and total volume storage space on the remote computer
$totalMemoryGb = Get-WmiObjectValue -PropertyName Capacity -WmiClassName Win32_PhysicalMemory -Session $session
$totalStorageGb = Get-WmiObjectValue -PropertyName FreeSpace -WmiClassName Win32_LogicalDisk -Session $session

Write-Host "The computer $($session.ComputerName) has $totalMemoryGb GB of memory and $totalStorageGb GB of free space across all volumes."

## Remove the shared session
Remove-PSSession -Session $session

스크립트를 저장하고 실행하십시오 (Get-InventoryInfo.ps1) 원하는 대로 작동하는지 확인합니다.

결론

이 튜토리얼에서는 재사용 가능한 세션을 사용하여 원격 컴퓨터를 효과적으로 관리하는 강력한 함수를 만드는 방법을 배웠습니다. 이제 여러 명령에 걸쳐 지속적인 연결을 유지하고 매번 연결을 끊지 않고 원격 시스템에서 복잡한 작업을 실행하는 방법을 알고 있습니다.

앞으로 이 지식을 바탕으로 재사용 가능한 세션을 더 큰 자동화 워크플로에 통합할 수 있습니다. 한 가지 예로는 인벤토리 기능을 확장하여 추가 시스템 메트릭을 수집하거나 여러 원격 머신에서 유지 관리 작업을 자동화하는 것입니다.

재사용 가능한 세션을 다른 PowerShell 기능과 결합하세요. 시간을 절약하고 수동 개입을 줄이기 위해 IT 관리 및 자동화 작업을 효율화하세요.

Source:
https://adamtheautomator.com/powershell-reusable-sessions/