PowerShell with a Purpose Blog

What To Do / Not to Do in PowerShell: Part 4

Can you tell me what the following command does?

gwmi win32_logicaldisk -fi 'drivetype=3' -com $x | ? { $_.freespace -lt 1gb } | % { $_.chkdsk() }

If you're a real PowerShell aficionado, you probably can. Newcomers, not so much. And either way, you have to spend a lot of time starting at it. Now, how about this one:

Get-WmiObject -class Win32_LogicalDisk -filter 'DriveType=3' -computername $computer |
Where-Object -filterScript { $_.FreeSpace -lt 1GB } |
ForEach-Object -process { $_.ChkDsk() }

Probably a lot easier to figure out. No, I don't know why you'd want to run a ChkDsk operation on disks that have less than 1GB of space free - that isn't the point. The point is that the second command is easier because I spelled out the cmdlet names and the parameter names, and I used a more sensible variable name. When you're at the command-line feel free to shorten things as much as you like; in a script - or when sharing on a blog, or when permanently saving anything for any reason - spell everything out completely. PowerShell can be difficult enough (look at all that punctuation you have to interpret!) without shortening the fairly-sensible cmdlet and parameter names into unintelligible symbols!

Srsly, will b ur bff if u do it rite.
Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish