Writing console output to a file - file is unexpectedly empty Writing console output to a file - file is unexpectedly empty powershell powershell

Writing console output to a file - file is unexpectedly empty


Guenther Schmitz' answer is effective, but it's worth explaining why:

  • Your Out-File -FilePath C:Filepath is a stand-alone command that receives no input.

    • An Out-File call with no input simply creates an empty file (0 bytes).
  • In order for cmdlets such as Out-File to receive input from (an)other command(s) (represented as ... below), you must use the pipeline, which means that you must place a | after the input command(s) and follow it with your Out-File call:
    Note that I'm using the shorter -Path parameter alias for the less commonly used -FilePath[1]

    ... | Out-File -Path C:Filepath
    • In the simplest case, as above, the entire command (pipeline) is placed on the same line; if you want to spread it across multiple lines for readability, you have have two choices:

      • Put a line break immediately after |, which tells PowerShell that the command continues on the next line:

        ... |  Out-File -Path C:Filepath
      • End a line with an explicit line continuation, which means placing ` at the very end of a line:

        ... `| Out-File -Path C:Filepath

Alternatively, since you're using Out-File with its default behavior, you could use >, an output redirection, instead:

... > C:Filepath

A couple of asides:

  • Using Out-File with something other than strings, and using Format-* cmdlets in general, means that the output is only suitable for display (human consumption), not for further programmatic processing.

  • If you want to send output to both the console and a file, use the Tee-Object cmdlet, as TobyU suggests:

    ... | Tee-Object -Path C:Filepath

[1] Strictly speaking, -LiteralPath is the best choice in this case, because -Path interprets its arguments as wildcard expressions. However, omitting -Path, i.e. specifying the file path as a positional argument, as is common, implicitly binds to -Path.


try this:

Get-VM xxxxx | Get-HardDisk |   Select Parent, Name, Filename, DiskType, Persistence |     Out-File -FilePath C:\Filepath