locked
Simple PowerShell redirect??? RRS feed

  • Question

  • OK, I'm used to Linux command shell and it is so easy to redirect output of a command to a file. But in powershell the results are objects that look great on the screen but terrible in a simple file.

    Consider the simple task of redirecting the output of history to file.txt

    In Linux Bash shell it's as easy as:

    history > file.txt

    When you open the file, it is exactly as I would expect it to be one command per line and no extra spaces anywhere.

    Now in powershell, I have no idea how to do this simple task because even after all of the following there are still a bunch of spaces after each command in the file. Very frustrating. How do you get rid of the spaces? Is there an easier way to go about this?

    history -Count 30 | select -Property Commandline | Format-Table -Hide | Out-File file.txt -Encoding ascii

    Tuesday, April 26, 2016 9:59 PM

Answers

  • 1) Don't use Format-Table. That adds formatting to the output (hence the name).

    2) If you want just the CommandLine property, use -ExpandProperty instead of just -Property. For example:


    history -c 30 | select -expand CommandLine

    If you have PowerShell 3.0 or later, you can apply some syntactic sugar:


    (history -c 30).CommandLine

    After that you can use > to redirect (Unicode output is the default) or pipe to Out-File (where you can specify encoding).


    -- Bill Stewart [Bill_Stewart]

    • Proposed as answer by FWN Wednesday, April 27, 2016 12:48 AM
    • Marked as answer by Bill_Stewart Monday, June 6, 2016 6:36 PM
    Tuesday, April 26, 2016 10:27 PM

All replies

  • 1) Don't use Format-Table. That adds formatting to the output (hence the name).

    2) If you want just the CommandLine property, use -ExpandProperty instead of just -Property. For example:


    history -c 30 | select -expand CommandLine

    If you have PowerShell 3.0 or later, you can apply some syntactic sugar:


    (history -c 30).CommandLine

    After that you can use > to redirect (Unicode output is the default) or pipe to Out-File (where you can specify encoding).


    -- Bill Stewart [Bill_Stewart]

    • Proposed as answer by FWN Wednesday, April 27, 2016 12:48 AM
    • Marked as answer by Bill_Stewart Monday, June 6, 2016 6:36 PM
    Tuesday, April 26, 2016 10:27 PM
  • Thank you for the quick reply. That was driving me crazy. I knew not to use the format command but then couldn't see how to get rid of the header without it. Your solution worked perfectly.
    Tuesday, April 26, 2016 10:52 PM