실제 모듈 만들기: 함수 만들기

시스템을 관리하면 한꺼번에 너무 많은 일을 처리하는 것 같은 느낌을 받을 수 있습니다. 한 분 동안은 저장 공간 문제를 해결하고, 다음 분에는 프로세서 사양을 찾거나 메모리 용량을 확인하고 있습니다. 이를 수동으로 처리하는 것은 귀찮을 뿐만 아니라 실수하기 쉽습니다. 이러한 사이클에 갇혀 있다면, 미친 것을 멈추는 때입니다. 자동화가 해답이 될 것입니다!

이 가이드에서는 PowerShell 함수를 작성하는 방법을 배워 워크플로우를 최적화하고 실제 중요한 부분에 집중할 수 있습니다.

전문가처럼 작동하고 시간을 절약할 수 있는 강력한 스크립트 모음을 즐기세요!

정보 추출을 위한 함수 작성

모듈을 확장하면 Get-CimInstance cmdlet을 사용하여 하드웨어 정보를 Info 속성에 채울 것입니다. 이 접근 방식을 통해 코드를 표준화하고 효과적으로 재사용할 수 있습니다.

다음 함수들은 원격 세션에서 메모리, 저장 공간 및 프로세서 정보를 수집합니다:

function Get-MemoryInfo {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [System.Management.Automation.Runspaces.PSSession]$Session
    )

    $outObject = @{
        'ComputerName'      = $Session.ComputerName
        'HardwareCategory'  = 'Memory'
        'Info'              = $null
    }

    $scriptBlock = {
        Get-CimInstance -ClassName Win32_PhysicalMemory
    }
    $result = Invoke-Command -Session $Session -ScriptBlock $scriptBlock

    $outObject['Info'] = $result
    [pscustomobject]$outObject
}

function Get-StorageInfo {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [System.Management.Automation.Runspaces.PSSession]$Session
    )

    $outObject = @{
        'ComputerName'      = $Session.ComputerName
        'HardwareCategory'  = 'Storage'
        'Info'              = $null
    }

    $scriptBlock = {
        Get-CimInstance -ClassName Win32_LogicalDisk
    }
    $result = Invoke-Command -Session $Session -ScriptBlock $scriptBlock

    $outObject['Info'] = $result
    [pscustomobject]$outObject
}

function Get-ProcessorInfo {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [System.Management.Automation.Runspaces.PSSession]$Session
    )

    $outObject = @{
        'ComputerName'      = $Session.ComputerName
        'HardwareCategory'  = 'Processor'
        'Info'              = $null
    }

    $scriptBlock = {
        Get-CimInstance -ClassName Win32_LogicalDisk
    }
    $result = Invoke-Command -Session $Session -ScriptBlock $scriptBlock

    $outObject['Info'] = $result
    [pscustomobject]$outObject
}

출력 변환

시스템 쿼리에서 검색한 원시 데이터에는 종종 필요 이상의 세부 정보가 포함되어 있어 해석하기 어려울 수 있습니다. 이러한 상황은 특정하고 실행 가능한 속성에 집중할 때 비효율성을 야기할 수 있습니다.

데이터를 표준화하기 위해 Get-CimInstance의 출력을 사용자 지정 객체로 변환할 수 있습니다.

다음은 업데이트된 버전입니다:

function Get-MemoryInfo {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [System.Management.Automation.Runspaces.PSSession]$Session
    )

    $outObject = @{
        'ComputerName'      = $Session.ComputerName
        'HardwareCategory'  = 'Memory'
        'Info'              = $null
    }

    $scriptBlock = {
        Get-CimInstance -ClassName Win32_PhysicalMemory
    }
    $result = Invoke-Command -Session $Session -ScriptBlock $scriptBlock

    $info = $result | ForEach-Object {
        [pscustomobject]@{
            'LocatorId' = $_.DeviceLocator
            'Capacity'  = $_.Capacity
        }
    }

    $outObject['Info'] = $info
    [pscustomobject]$outObject
}

function Get-StorageInfo {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [System.Management.Automation.Runspaces.PSSession]$Session
    )

    $outObject = @{
        'ComputerName'      = $Session.ComputerName
        'HardwareCategory'  = 'Storage'
        'Info'              = $null
    }

    $scriptBlock = {
        Get-CimInstance -ClassName Win32_LogicalDisk
    }
    $result = Invoke-Command -Session $Session -ScriptBlock $scriptBlock

    $info = $result | ForEach-Object {
        [pscustomobject]@{
            'VolumeName'      = $_.VolumeName
            'VolumeLetter'    = $_.DeviceId
            'VolumeCapacity'  = $_.Size
            'VolumeFreeSpace' = $_.FreeSpace
        }
    }

    $outObject['Info'] = $info
    [pscustomobject]$outObject
}

바이트 값 처리

하드웨어 정보에는 주로 바이트 단위의 메모리 또는 저장 용량과 같은 숫자 값이 포함됩니다. 기술적으로 정확하지만, 이러한 값들은 빠른 해석을 위해 더 실용적일 수 있습니다. 기가바이트로 변환하면 하드웨어 지표에 대한 직관적인 이해가 가능해집니다.

더 읽기 쉽도록, 도우미 함수 ConvertTo-Gb를 사용하면 이 과정을 효율적으로 만들 수 있습니다:

function ConvertTo-Gb {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Bytes
    )

    $numberGb = $Bytes / 1GB
    [math]::Round($numberGb, 2)
}

function Get-MemoryInfo {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [System.Management.Automation.Runspaces.PSSession]$Session
    )

    $outObject = @{
        'ComputerName'      = $Session.ComputerName
        'HardwareCategory'  = 'Memory'
        'Info'              = $null
    }

    $scriptBlock = {
        Get-CimInstance -ClassName Win32_PhysicalMemory
    }
    $result = Invoke-Command -Session $Session -ScriptBlock $scriptBlock

    $info = $result | ForEach-Object {
        [pscustomobject]@{
            'LocatorId' = $_.DeviceLocator
            'Capacity'  = (ConvertTo-Gb -Bytes $_.Capacity)
        }
    }

    $outObject['Info'] = $info
    [pscustomobject]$outObject
}

이 접근 방식은 이러한 함수에 의해 반환된 데이터의 기능성과 가독성을 향상시킵니다. 미래의 업데이트나 변경 사항은 ConvertTo-Gb와 같은 도우미 함수로 반복적인 논리를 중앙 집중화함으로써 더 쉽게 관리할 수 있습니다.

결론

이 안내서에 나와 있는 단계를 사용하여 PowerShell 함수를 만드는 방법을 배웠습니다. 원격 시스템에서 하드웨어 정보를 수집하거나 원시 출력을 구조화된 사용자 정의 객체로 변환하거나 데이터를 더 읽기 쉽게 만드는 방법이 있습니다.

이러한 기술을 습득했으므로, 이 기반을 확장하는 방법을 고려해 보세요. 예를 들어 네트워크 어댑터나 GPU 정보와 같은 더 많은 하드웨어 카테고리를 모듈에 추가할 수 있습니다. 또한 시스템 상태 모니터링이나 재고 관리와 같은 더 큰 자동화 워크플로에 이러한 함수를 통합할 수도 있습니다.

가능성은 무한하며, 시스템을 자신있게 관리하기 위한 견고한 도구 세트를 구축하는 길에 꽤 잘 나가고 있습니다.

Source:
https://adamtheautomator.com/powershell-functions-module/