String Manipulation, just can't get this one!

Hi, What I am doing is quite simple, but I get bogged down in strings. Basically I am doing this:

-getting all of the vm names from VMware which exist on a datastore. What I need are those names to become an array with a comma after each so that I can do a foreach. I need to remove the top 2 lines of the csv file because they are headers and such. Here has been my attempt. When I go to the foreach section, the variable is seen as a long string of characters instead of individual names I can do something with. Proably a lot of redundancy in here :slight_smile: -

$datastore = “datastore”
$filename = “c:\scripts\output$datastore.csv”
$ds = get-datastore $datastore | get-vm | select name
$ds | Convertto-csv | select -skip 2 | out-string | out-file $filename
$ds = (gc “c:\scripts\output$datastore.csv”) -join “,”
$result += $ds

I can see there is issue when I test this.

Foreach ($vm in $result)
write-output $vm

Thanks for whomever helps me, I know it’s probably something I am REALLY overlooking :slight_smile:


I think you shouldn’t need to export any of the data to CSV to be honest. The item that will be returned to you will be a collection, so you can already use a foreach.

-expandproperty name 
will mean that you will get a collection with just the values that are in the name column.

$datastore = "datastore"
$ds = get-datastore $datastore | get-vm | select -expandproperty name

Write-Output $psitem

Thanks, but I do want to export all of the datastores and vms to a file first… I actually want to manipulate the data so that I am only moving a few vms on each datastore simultaneously…

Perhaps you could give us an example of how your CSV looks like (say top 10 lines) and a representation of what you expect it to look like?

I’ll second that, it would help tremendously.

Having another look at the code, it also looks like you’ve a syntax error if you’re trying to define $result as an array.


should be

$result = @()

You are reading the rows in your CSV-file as text and combining all rows to one row using -join.

I don’t really see the purpose of using the CSV. How about using the following code:

$Result = Get-Datastore -Name $Datastore | Get-VM
Foreach($VM in $Result)
   Write-output $VM.Name

If you really want to export the names to a file and read it back again I’d recommend the following approach:

$datastore = "datastore"
$filename = "c:\scripts\output\$datastore.txt"
$ds = get-datastore $datastore | get-vm | select -expandproperty name | out-file $filename
$ds = (gc "c:\scripts\output\$datastore.txt")
$result += $ds

Great, thanks Everyone. I ended up using Simon’s suggestion. Thanks!