Ad Space here

Welcome Guest! To enable all features please Login or Register.

Notification

Icon
Error

Share
Options
Go to last post Go to first unread
Dustin Higgins  
#1 Posted : Monday, April 13, 2020 10:40:45 PM(UTC)
Dustin Higgins

Rank: Advanced Member

Groups: Registered
Joined: 7/1/2018(UTC)
Posts: 62
_United States

Thanks: 1 times
Was thanked: 6 time(s) in 6 post(s)

PowerShell CIM Disk Space Query

The PowerShell CIM Disk Space Query retrieves free disk space (in GB and percent free) on local and remote computers. The CIM connection uses DCOM only because WSMan has typically not been available where I have been working. I thought I would try something a little different (for me) with this one and record just the code. There are bullets on key parts of the code. There is also a quick demonstration of the script at the end. #dhbscripting #PowerShell

Main Script Parameters:

Code:
param (
	[Parameter(Mandatory=$false)]
	[string]$Computer,
	[Parameter(Mandatory=$false)]
	[int]$Timeout = 30
)

Code:
function Get-CimSessionDcom
{
	<#
	.SYNOPSIS
	Function to return a DCOM CIM Session.
	.DESCRIPTION
    Function to return a DCOM CIM Session.  This is hard-coded to DCOM because
    there is zero percent chance of the WSMan service being used in my environment.
	#>
	param (
		[Parameter(Mandatory=$true)]
		[string]$Computer,
		[Parameter(Mandatory=$true)]
		[int]$Timeout
	)
	# Setup the object
	$Obj = [PSCustomObject]@{
		CimSession = $null
		Exception = $null
		ObjTimestamp = (Get-Date)
	}
	# Create the CIM session (Use DCOM since WsMan/PS Remoting is turned off)
	$Options = New-CimSessionOption -Protocol Dcom
	# Setup the parameters
	$RemoteParams = @{
		ComputerName = $Computer
	}
	$SessionParams = @{
		SessionOption = $Options
		OperationTimeoutSec = $Timeout
		ErrorAction = "Stop"
	}
	# Create the session
	try {
		$CimSession = New-CimSession @SessionParams @RemoteParams
        $Obj.CimSession = $CimSession
	} catch {
		$Obj.Exception = $_
	}
	# Return the object
	Return $Obj
}

Code:
function Get-OnlineStatusPing
{
    <#
    .SYNOPSIS
    Function retrieve online status using the ping command.
    .DESCRIPTION
    Function retrieve online status using the ping command.  I personally don't use 
    Test-Connection because sometimes it throws cryptic errors that are hard to catch 
    and deal with.  Pick a way, learn it inside and out and be confident.  That is what I did.
    #>
    param (
        [Parameter(Mandatory=$true)]
        [string]$Computer
	)
	# Setup the object
	$Obj = [PSCustomObject]@{
		Computer = $Computer
		Online = $null
		PingResult = $null
	}
    # Check the Online Status - Return if offline
    $Obj.PingResult = ping -n 1 -4 $computer
    if ($?) {
        if ($pingStatus -match "unreachable" -or $pingStatus -match "could not find host" -or $pingStatus -match "timed out") {
            $Obj.Online = $false
        } else {
            $Obj.Online = $true
        }
    } else {
        $Obj.Online = $false
    }
	# Return the object
	Return $Obj
}

Code:
function Get-CimDiskSpace
{
    <#
    .SYNOPSIS
    Function retrieve disk space status from a CIM query.
    .DESCRIPTION
    Function retrieve disk space status from a CIM query.  This function
    queries disk space through a CIM query and returns the results in GB
    and percent free so it is easy to determine whether or not action needs
    to be taken.
    #>
    param (
        [Parameter(Mandatory=$true)]
        [string]$Computer,
        [Parameter(Mandatory=$true)]
        [int]$Timeout
    )
	# Setup the object
    $Obj = [PSCustomObject]@{         
        Computer = $Computer
        Online = $null
        C_Size = $null
        C_UsedSpace = $null
        C_FreeSpace = $null
        C_PercentFree = $null
        LogicalDisk = New-Object System.Collections.Generic.List[PSObject]
		CimCmds = New-Object System.Collections.Generic.List[PSObject]
		Exception = $null
        ObjTimeStamp = (get-date)
    }
    # Check the ping status - return if offline
	$OnlineStatusObj = Get-OnlineStatusPing -Computer $Computer
	$Obj.Online = $OnlineStatusObj.Online
	if ($Obj.Online -eq $false) {
		Return $Obj
	}
	# Get the CIM session - return if there is an exception
	$CimSessionObj = Get-CimSessionDcom -Computer $Computer -Timeout $Timeout
	if ($null -ne $CimSessionObj.Exception) {
		$Obj.Exception = $CimSessionObj.Exception
		Return $Obj
	}
	# Query for Disk Space
	$Params = @{
		Query = "SELECT DeviceId, DriveType, ProviderName, FreeSpace, Size, VolumeName From Win32_LogicalDisk"
		NameSpace = "root\cimv2"
		CimSession = $CimSessionObj.CimSession
		OperationTimeoutSec = $Timeout
		ErrorAction = "Stop"
	}
	try {
		$CimResultObj = Get-CimInstance @Params
	} catch {
		$Obj.Exception = $_
		Return $Obj
	}
	# Add the cmd to the list
	$Obj.CimCmds.Add($CimResultObj)
	# Process the Drives
	foreach ($i in $CimResultObj) {
		if ($i.DriveType -eq 3) {
			$FreeGB = [math]::Round(($i.FreeSpace / 1GB), 2)
			$SizeGB = [math]::Round(($i.Size / 1GB), 2)
			$DiskObj = [PSCustomObject]@{
				DeviceId = $i.DeviceId
				DriveType = $i.DriveType
				ProviderName = $i.ProviderName
				FreeSpace = $i.FreeSpace
				FreeSpace_GB = $FreeGB
				Size = $i.Size
				Size_GB = $SizeGB
				VolumeName = $i.VolumeName
			}
			if ($i.DeviceId -eq "C:") {
				$Obj.C_Size = $SizeGB
				$Obj.C_UsedSpace = [math]::Round(($SizeGB - $FreeGB), 2)
				$Obj.C_FreeSpace = $FreeGB
				$Obj.C_PercentFree = [math]::Round(($FreeGB / $SizeGB) * 100, 2)
			}
			$Obj.LogicalDisk.Add($DiskObj)
		}
	}
	# Remove the CIM Session
	Remove-CimSession -CimSession $CimSessionObj.CimSession
	# Return the object
	Return $Obj    
}

Code:
#####################################################
# MAIN
#####################################################
# Set the computer name (default to the local computer if not passed)
if ($PSBoundParameters.ContainsKey("Computer") -eq $false) {
	$Computer = $env:COMPUTERNAME
}
# Call the function
$Result = Get-CimDiskSpace -Computer $Computer -Timeout $Timeout
# Return the result
$Result

Follow Dustin Higgins ​​​​​​​on Twitter and Instagram

Sponsor
Ad Space here
Rss Feed  Atom Feed
Users browsing this topic
Forum Jump  
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.