a.smith
a.smith

Reputation: 315

How to create a variable from specific part of command output in powershell script

PowerShell script runs a command to give me total bytes and total free bytes of my harddisk. I want to pick those two returned values as variables to do some calculations with but I'm not sure how to set a variable to a specific part of a command's output.

After looking through similar questions I cant apply the same logic to my situations. I have never used PowerShell before and not very familiar with Windows servers. Any recommended tutorials would be welcomed.

fsutil volume diskfree C:

Total # of free bytes : 1234567

Total # of bytes: 7654321

Upvotes: 2

Views: 688

Answers (3)

Lieven Keersmaekers
Lieven Keersmaekers

Reputation: 58441

Get-WmiObject as mentioned in the other answers is the way to go but for the fun of it

$freespace, $size = [int64[]]((fsutil volume diskfree C:)[0,1] -split ': ')[1,3]
Write-Output $freespace, $size

Disclaimer: note that this breaks when microsoft decides to change the output format of fsutil

Upvotes: 2

Mark Harwood
Mark Harwood

Reputation: 2415

I would instead use PowerShell's Get-WmiObject command and look at the Win32_LogicalDisk class. You could do something like this:

$cDrive = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceId='C:'"

That way you can get the free space and size attributes of the drive and manipulate them however you like. For example, this would show you the free space on the C drive in GB:

[Math]::Round( $cDrive.FreeSpace / 1GB)

Upvotes: 3

EylM
EylM

Reputation: 6103

You can use WMI from Powershell.

$diskData = Get-WmiObject Win32_LogicalDisk -Filter "DeviceID='C:'" | Select-Object Size, FreeSpace

Write-Host $diskData.Size
Write-Host $diskData.FreeSpace

Upvotes: 3

Related Questions