リアルワールドモジュールの作成:関数の作成

システムの管理は一度に多くのことをこなしているような感じになることがあります。一瞬はストレージの問題のトラブルシューティングをしていて、次の瞬間にはプロセッサの仕様を調べたり、メモリ容量を確認したりしています。手作業でこれを行うことは単調であり、ミスを起こしやすいです。もし、このサイクルに囚われているのであれば、狂気を止める時がきたのです。自動化がその答えです!

このガイドでは、PowerShell関数を構築する方法を学び、ワークフローを効率化し、本当に重要なことに集中できるようになります。

プロと同様に操作するための強力なスクリプトセットを楽しんで、時間を節約しましょう。

情報を抽出するための関数の構築

モジュールを拡張していく過程で、Get-CimInstanceコマンドレットを使用してハードウェア情報を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/