user152949
user152949

Reputation:

Multiple pipes in Powershell

How can I process multiple commands on the same item; take this example where I want to display both the filename and the last write date but only the filename appears:

PS C:\Users\demo> ls *.zip | % { Write-Host $_.FullName }  | % { Write-Host $_.LastTimeWrite }
C:\Users\demo\archive.zip

Upvotes: 4

Views: 9783

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 58931

first, the FileInfo property is called LastWriteTime - not LastTimeWrite.

You could use a format string, like:

ls *.zip | % { Write-Host ("{0} {1}" -f $_.FullName, $_.LastWriteTime) }

Or you use a semicolon to separate the commands:

ls *.zip | % { Write-Host $_.FullName; Write-Host $_.LastWriteTime }

In case of Write-Host, you can also write

ls *.zip | % { Write-Host $_.FullName $_.LastWriteTime }

The reason why your pipeline doesn't work as you expect is two-fold:

  • Write-Host writes output to the host environment (i.e. the console), so there's nothing left to go into the next pipeline step. Use Write-Output or Select-Object instead of Write-Host if you need to further process the results.
  • Even if you didn't write the output to the host environment, the next step in the pipeline wouldn't have the same in put as the current step, because you're transforming the FileInfo objects into strings in the current step.

Upvotes: 6

Related Questions