简体   繁体   中英

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

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)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM