Feeding Input Into Native Commands

by Jul 15, 2009

Sometimes, you need to call commands that require interactive input to work. For example, to find out existing drives with DiskPart, you would have to start DiskPart and then interactively type the command:

list disk

A little known feature of PowerShells pipeline is the ability to feed required input into commands that would otherwise expect input to be entered interactively. So to get a list of drives without interaction, use this line:

"list disk" | DiskPart

You can then process the results with Where-Object and filter out any unwanted information. For example:

"list disk" | DiskPart | Where-Object { $_.StartsWith(" ") }

Be aware that DiskPart requires Admin privileges. On Vista and above with UAC, make sure you launch PowerShell with elevated rights in the first place or else DiskPart will elevate itself and break the pipeline.

This feature works for all commands requiring interactive input, and you can even submit more than one command:

@'
select disk 0
detail disk
'@ | DiskPart