I'm new to scripting and I am trying to write the information returned about a VM to a text file. My script looks like this:
Connect-VIServer -Server 192.168.255.255 -Protocol https -User xxxx -Password XXXXXX
Get-VM -Name xxxxxx
Get-VM xxxxx | Get-HardDisk | Select Parent, Name, Filename, DiskType, Persistence | FT -AutoSize
Out-File -FilePath C:Filepath
I am able to connect to the VM, retrieve the HDD info and see it in the console. The file is created where I want it and is correctly named. No data is ever put into the file. I have tried Tee-Object with the same results. I've also tried the -append switch. I did see a post about the data being returned as an array and Powershell is not able to move the data from an array to a string. Do I need to create a variable to hold the returned data and write to file from there?
Thanks
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With