Tuesday, June 25, 2024
HomePowershellConstructing a Laptop Stock Report

Constructing a Laptop Stock Report


PowerShell tool-building is an important a part of studying to go from a replica/paste scripter to somebody that may construct actual, reusable scripts. For instance of a tool-building methodology, let’s construct a easy laptop stock report instrument that can stroll you thru the method of constructing a easy but efficient instrument utilizing PowerShell.

We’ll begin with studying information from a CSV file, then question laptop particulars utilizing CIM, and eventually output the outcomes right into a structured format. Let’s get began!

Step 1: Studying and Processing a CSV File

First, we have to arrange the environment. We’ll create a pattern CSV file containing a pc title and deparment that laptop could also be in. I’ll additionally create a clean script known as Begin-ComputerInventoryReport.ps1.

# Pattern CSV content material
@'
ComputerName,Division
PC1,HR
PC2,Finance
'@ | Set-Content material -Path C:computer systems.csv

Set-Content material -Path C:Begin-ComputerInventoryReport.ps1 -Worth ''

Subsequent, open up C:Begin-ComputerInventoryReport.ps1 in your favourite editor and let’s get scripting!

First, learn the computer systems right into a CSV file. You need to see every CSV row.

$computer systems = Import-Csv -Path C:computer systems.csv
$computer systems

It will import our CSV file and retailer the info within the $computer systems variable.

Step 2: Including a Connection Verify

I at all times suggest beginning small; begin with a single object after which construct upon that. So begin working with a single laptop and get the entire code down.

Since our script will question distant computer systems, it’s an excellent apply to test if the pc is on-line earlier than continuing:

Check-Connection -ComputerName $computer systems[0].ComputerName -Rely 1 -Quiet

This command will return True if the machine is on-line and False in any other case.

Step 3: Processing Every Laptop

To deal with a number of computer systems, we’ll use a foreach loop:

foreach ($laptop in $computer systems) {
    Write-Host "Processing the [$($computer.ComputerName)] laptop."
}

For now, let’s deal with a single laptop by briefly adjusting our loop:

foreach ($laptop in $computer systems[0]) {
    Write-Host "Processing the [$($computer.ComputerName)] laptop."
}

Step 4: Creating the Output Object

We wish to collect the ComputerName, Division, and IsOnline properties. Let’s create a hashtable and convert it to a customized object:

foreach ($laptop in $computer systems[0]) {
    $output = @{
        ComputerName = $laptop.ComputerName
        Division   = $laptop.Division
        IsOnline     = $null
    }
    [pscustomobject]$output
}

Now, populate the IsOnline property utilizing the Check-Connection command:

foreach ($laptop in $computer systems[0]) {
    $output = @{
        ComputerName = $laptop.ComputerName
        Division   = $laptop.Division
        IsOnline     = $null
    }

    $isOnline = Check-Connection -ComputerName $laptop.ComputerName -Rely 1 -Quiet
    $output.IsOnline = $isOnline
    [pscustomobject]$output
}

Step 5: Processing All Computer systems

Lastly, take away the momentary single laptop focus and course of all computer systems:

foreach ($laptop in $computer systems) {
    $output = @{
        ComputerName = $laptop.ComputerName
        Division   = $laptop.Division
        IsOnline     = $null
    }

    $isOnline = Check-Connection -ComputerName $laptop.ComputerName -Rely 1 -Quiet
    $output.IsOnline = $isOnline
    [pscustomobject]$output
}

Step 6: Including CIM Question

Let’s prolong our instrument to assemble further data such because the producer, mannequin, CPU rely, and complete RAM from every laptop utilizing the CIM class Win32_ComputerSystem:

foreach ($laptop in $computer systems) {
    $output = @{
        ComputerName = $laptop.ComputerName
        Division   = $laptop.Division
        IsOnline     = $null
        Producer = $null
        Mannequin        = $null
        CPUCount     = $null
        TotalRAM     = $null
    }

    $isOnline = Check-Connection -ComputerName $laptop.ComputerName -Rely 1 -Quiet
    $output.IsOnline = $isOnline

    if ($isOnline) {
        $systemInfo = Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $laptop.ComputerName
        $output.Producer = $systemInfo.Producer
        $output.Mannequin        = $systemInfo.Mannequin
        $output.CPUCount     = $systemInfo.NumberOfProcessors
        $output.TotalRAM     = $systemInfo.TotalPhysicalMemory
    }

    [pscustomobject]$output
}

Step 7: Refactoring Utilizing the Pipeline

To make our instrument extra versatile, let’s refactor it to just accept enter from the pipeline. This permits us to make use of varied information sources, not simply CSV recordsdata:

[CmdletBinding()]
param(
    [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
    [string]$ComputerName
)

course of {
    $output = @{
        ComputerName = $ComputerName
        IsOnline     = $null
        Producer = $null
        Mannequin        = $null
        CPUCount     = $null
        TotalRAM     = $null
    }

    $isOnline = Check-Connection -ComputerName $ComputerName -Rely 1 -Quiet
    $output.IsOnline = $isOnline

    if ($isOnline) {
        $systemInfo = Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $ComputerName
        $output.Producer = $systemInfo.Producer
        $output.Mannequin        = $systemInfo.Mannequin
        $output.CPUCount     = $systemInfo.NumberOfProcessors
        $output.TotalRAM     = $systemInfo.TotalPhysicalMemory
    }

    [pscustomobject]$output
}

Now you can pipe information from varied sources:

Get-ADComputer -Filter * -SearchBase "OU=IT, DC=contoso, DC=com" |
Choose-Object -Property *,@{n='ComputerName';e={$_.Identify}} -ExcludeProperty Identify |
C:Begin-ComputerInventoryReportv4.ps1

Step 8: Saving Output to CSV

Let’s add performance to save lots of the output to a CSV file:

[CmdletBinding()]
param(
    [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
    [string]$ComputerName,

    [Parameter()]
    [string]$OutputFilePath
)

course of {
    $output = @{
        ComputerName = $ComputerName
        IsOnline     = $null
        Producer = $null
        Mannequin        = $null
        CPUCount     = $null
        TotalRAM     = $null
    }

    $isOnline = Check-Connection -ComputerName $ComputerName -Rely 1 -Quiet
    $output.IsOnline = $isOnline

    if ($isOnline) {
        $systemInfo = Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $ComputerName
        $output.Producer = $systemInfo.Producer
        $output.Mannequin        = $systemInfo.Mannequin
        $output.CPUCount     = $systemInfo.NumberOfProcessors
        $output.TotalRAM     = $systemInfo.TotalPhysicalMemory
    }

    $out = [pscustomobject]$output
    if ($PSBoundParameters.ContainsKey('OutputFilePath'))  Export-Csv -Path $OutputFilePath -Append
    
    $out
}

Step 9: Including Error Dealing with

Lastly, let’s add error dealing with to make our script extra strong:

[CmdletBinding()]
param(
    [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
    [string]$ComputerName,

    [Parameter()]
    [string]$OutputFilePath
)

start {
    $ErrorActionPreference = 'Cease'
}

course of {
    strive {
        $output = @{
            ComputerName = $ComputerName
            IsOnline     = $null
            Producer = $null
            Mannequin        = $null
            CPUCount     = $null
            TotalRAM     = $null
            Error        = $null
        }

        $isOnline = Check-Connection -ComputerName $ComputerName -Rely 1 -Quiet
        $output.IsOnline = $isOnline

        if ($isOnline) {
            $systemInfo = Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName $ComputerName
            $output.Producer = $systemInfo.Producer
            $output.Mannequin        = $systemInfo.Mannequin
            $output.CPUCount     = $systemInfo.NumberOfProcessors
            $output.TotalRAM     = $systemInfo.TotalPhysicalMemory
        }

        $out = [pscustomobject]$output
    }
    catch {
        $output.Error = $_.Exception.Message
        $out = [pscustomobject]$output
    }
    lastly {
        if ($PSBoundParameters.ContainsKey('OutputFilePath'))  Export-Csv -Path $OutputFilePath -Append
        
        $out
    }
}

By following these steps, you’ve gotten constructed a complete instrument for producing a pc stock report utilizing PowerShell. This instrument can learn from varied sources, question system data, deal with errors, and export the outcomes to a CSV file. Pleased scripting!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments