LLMA-dot / Get-Clue

Collection of various links and other useful things that I am currently learning. Maybe helpful to others.
0 stars 0 forks source link

Behind the PS Pipeline: The Value of Objects #5

Closed LLMA-dot closed 1 year ago

LLMA-dot commented 1 year ago

https://jeffhicks.substack.com/p/the-value-of-objects

The Value of Objects

Try:

$computername = Read-Host "Enter a computername" $Query = "Select * from win32_logicaldisk where drivetype=3" Get-WmiObject -Query $Query -ComputerName $computername | Select-Object -property DeviceID,Size,Freespace, @{Name="PercentFree";Expression = {$_.freespace/$_.size}}

Get all fixed logical disks from a remote computer. Select the computername, drive letter, size in GB, free space and percent free space and export to a CSV file.

Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DriveType=3" -ComputerName $computername |
Select-Object -property DeviceID,@{Name="SizeGB";Expression = {$_.size/1GB -as [int32]}},
Freespace,@{Name="PercentFree";Expression = {($_.freespace/$_.size)*100}},SystemName |
Export-CSV c:\work\diskinfo.csv -Append

Try: @{Name="PercentFree";Expression = {"{0:p2}" -f ($_.freespace/$_.size)}} Try: @{Name="PercentFree";Expression = {[math]::round(($_.freespace/$_.size)*100,2)}}

Functions write Objects

Okay...

Function Get-PercentFree {
Param($Drive="C:",$Computername=$env:COMPUTERNAME)

$d = Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DeviceID='$Drive'" -ComputerName $computername
$p = [math]::round(($d.freespace/$d.size)*100,2)
return $p
}

... but this is better:


Function Get-LogicalDisk {
[cmdletbinding()]
Param($Computername=$env:COMPUTERNAME)

$disks = Get-CimInstance -ClassName Win32_LogicalDisk -Filter "DriveType=3" -ComputerName $computername
$disks | Select-Object @{Name="Computername";Expression={$_.SystemName}},
DeviceID,Size,FreeSpace,@{Name="PercentFree";Expression = {[math]::round(($_.freespace/$_.size)*100,2)}},
@{Name="Audit";Expression = {Get-Date}}

}

Image

$data = "prospero","thinkx1-jh","dom1","srv2" | 
Foreach-Object { Get-LogicalDisk -Computername $_ }
foreach ($item in $data) {
 $line = "[{0:d}] Drive {1} on {2} is {3}% free" -f $item.Audit,$item.DeviceID,$item.computername,$item.percentfree
 $line
 #$line | Out-File log.txt -append
}

Image