martind
martind

Reputation: 41

How to use cmd type pipe (/piping) in PowerShell?

In cmd (and bash), pipe "|" pushes output to another command in the original format of the first command's output (as string).

In PowerShell, everything that comes out the pipe is an object (even a string is a string object).

Because of that, some commands fail when run in a PowerShell command window as opposed to a Windows command window.

Example:

dir c:\windows | gzip > test.gz

When this command is run in the Windows command prompt window it works properly - directory listing of C:\windows gets compressed into test.gz file.

The same command in PowerShell fails, because PowerShell does not use cmd-style pipe and replaces it with PowerShell pipe (working with array of file system items).

Q. How do you disable the default piping behavior in PowerShell to make traditional Windows commands work identically in PowerShell?

I tried using the escape character "`" before the pipe "`|", but it didn't work. I also tried invoke-expression -command "command with | here", but it also failed.

Upvotes: 4

Views: 15554

Answers (4)

TallGuy
TallGuy

Reputation: 1953

If you really need to use the old school DOS pipe system in PowerShell, it can be done by running a command in a separate, temporary DOS session:

& cmd /c "dir c:\windows | gzip > test.gz"

The /c switch tells cmd to run the command then exit. Of course, this only works if all the commands are old school DOS - you can't mix-n-match them with PowerShell commands.

While there are PowerShell alternatives to the example given in the question, there are lots of DOS programs that use the old pipe system and will not work in PowerShell. svnadmin load is one that I've the pleasure of having to deal with.

Upvotes: 1

OldFart
OldFart

Reputation: 2479

If you can pipe the output of (CMD) dir into gzip, then gzip apparently knows how to parse dir output. The (string) output from the PowerShell dir command (aka Get-ChildItem) doesn't look the same, so gzip likely would not be able to parse it. But, I'd also guess that gzip would be happy to take a list of paths, so this would probably work:

dir c:\windows | select -ExpandProperty FullName | gzip > test.gz

No warrantees express or implied.

Upvotes: 4

Aaron Jensen
Aaron Jensen

Reputation: 26809

You can't. PowerShell was designed to pass objects down a pipeline, not text. There isn't a backwards-compatability mode to DOS.

Upvotes: 0

Andy Schneider
Andy Schneider

Reputation: 8684

if you want to send strings down the pipeline you can use the cmdlet "out-string"

For Example:

get-process | out-string

If you are specifically looking for a PowerShell way to zip up files, check out the PowerShell Community Extensions. there are a bunch of cmdlets to zip and unzip all kinds of files.

http://pscx.codeplex.com

Upvotes: 8

Related Questions