VMware Cloud Community
Mike_Pownall
Contributor
Contributor
Jump to solution

Read & Write from a file

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 -


test01vm test02vm test03vm

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 -


is switched off test01vn is switched off test02vm is switched off test03vm is switched off is switched off 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

Reply
0 Kudos
1 Solution

Accepted Solutions
LucD
Leadership
Leadership
Jump to solution

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

View solution in original post

Reply
0 Kudos
2 Replies
LucD
Leadership
Leadership
Jump to solution

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

Reply
0 Kudos
Mike_Pownall
Contributor
Contributor
Jump to solution

Thanks that's perfect!

Reply
0 Kudos