Chapters/converting-a-function-to-a-class/Coded.ps1

class ToolmakingMachineInfo {

    # Properties
    [string]$ComputerName
    [string]$OSVersion
    [string]$SPVersion
    [string]$OSBuild
    [string]$Manufacturer
    [string]$Model
    [string]$Procs
    [string]$Cores
    [string]$RAM
    [string]$SysDriveFreeSpace
    [string]$Arch

    # Constructors
    ToolmakingMachineInfo([string]$ComputerName, [string]$Protocol) {
            
        if ($protocol -eq 'Dcom') {
            $option = New-CimSessionOption -Protocol Dcom
        } else {
            $option = New-CimSessionOption -Protocol Wsman
        }
 
        Try {
            $params = @{'ComputerName'=$Computername
                        'SessionOption'=$option
                        'ErrorAction'='Stop'}
            $session = New-CimSession @params
  
            $os_params = @{'ClassName'='Win32_OperatingSystem'
                           'CimSession'=$session}
            $os = Get-CimInstance @os_params

            $cs_params = @{'ClassName'='Win32_ComputerSystem'
                           'CimSession'=$session}
            $cs = Get-CimInstance @cs_params

            $sysdrive = $os.SystemDrive
            $drive_params = @{'ClassName'='Win32_LogicalDisk'
                              'Filter'="DeviceId='$sysdrive'"
                              'CimSession'=$session}
            $drive = Get-CimInstance @drive_params

            $proc_params = @{'ClassName'='Win32_Processor'
                             'CimSession'=$session}
            $proc = Get-CimInstance @proc_params |
                    Select-Object -first 1

            $session | Remove-CimSession
  
            $this.ComputerName=$computername
            $this.OSVersion=$os.version
            $this.SPVersion=$os.servicepackmajorversion
            $this.OSBuild=$os.buildnumber
            $this.Manufacturer=$cs.manufacturer
            $this.Model=$cs.model
            $this.Procs=$cs.numberofprocessors
            $this.Cores=$cs.numberoflogicalprocessors
            $this.RAM=($cs.totalphysicalmemory / 1GB)
            $this.Arch=$proc.addresswidth
            $this.SysDriveFreeSpace=$drive.freespace

        } Catch {
            throw "Failed to connect to $computername on $protocol"
        } #try/catch
    }

} #class

New-Object -TypeName ToolmakingMachineInfo -ArgumentList "localhost","wsman"