Hi,
I'm new to powershell and I just cannot seem to get my head around writing to a file then reading back in.
This is my code.
get-vm | where { $_.PowerState -eq "PoweredOff" } | select Name | out-file test.txt
The file contains the following.
Name -
with an empty line at the begining and 2 empty lines at the end.
When I read back from the file using.
$offvms = get-content $outfile foreach ($offvm in $offvms) { write-host "$offvm is switched off" }
I get the following output.
is switched off Name is switched off -
What am I missing here? What I want is to create the file with only the names of the vm's powered off, then read them back later.
Hope this makes sense, any help would be really appreciated.
Thanks
The Out-File cmdlet just writes what normally would appear on screen to a file.
The problem you're seeing is caused by the Select-Object cmdlet.
This cmdlet formats the data (blank lines, header, underligned...).
If you just want to save the names of the guests in a file you better do it like this
get-vm | where { $_.PowerState -eq "PoweredOff" } | %{$_.Name} | Set-Content test.txt
And then this will work like you expected.
$offvms = get-content test.txt foreach ($offvm in $offvms) { write-host "$offvm is switched off" }
____________
Blog: LucD notes
Twitter: lucd22
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
The Out-File cmdlet just writes what normally would appear on screen to a file.
The problem you're seeing is caused by the Select-Object cmdlet.
This cmdlet formats the data (blank lines, header, underligned...).
If you just want to save the names of the guests in a file you better do it like this
get-vm | where { $_.PowerState -eq "PoweredOff" } | %{$_.Name} | Set-Content test.txt
And then this will work like you expected.
$offvms = get-content test.txt foreach ($offvm in $offvms) { write-host "$offvm is switched off" }
____________
Blog: LucD notes
Twitter: lucd22
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Thanks that's perfect!