Today, I was working on creating a script that updates some of our Student Information System core files on some workstations, and since my whole environment is based on VMWare View, I had to find a way to get the constantly changing VM numbers to be reported to the script which is supposed to update these files.

My method was to write a PowerShell script using the vSphere PowerCLI tools to get all my VMs and format them to get the total number of powered on VMs in a specific resource pool, as well as which workstations are actually available.

(Since I’m using VMWare View in a non-peristent pool, and having the VMs destroyed after the first log off, it’s hard to keep track what is on, and off, and the sequence of the workstation names is not necessarily always in order. )

Well, the script was simple:

   1:  Add-PSSnapin VMware.VimAutomation.Core
   2:  Connect-VIServer -Server do-vsphere
   3:  Get-ResourcePool "Aeries View Devel" | Get-VM | grep -c -i "AeriesCS-SB-*" \
   4:  | Out-File "\\server\share$\VMCount.txt"
   5:  $VMArray = Get-ResourcePool "Aeries View Devel" | Get-VM | grep -i "AeriesCS-SB*" |sort
   6:  
   7:  foreach ($VM in $VMArray)
   8:  {
   9:      $VM = $VM.substring(0, 15)
  10:      $VM = $VM.substring($VM.Length - 3, 3)
  11:      $VM | Out-File -append "\\server\share$\VMCount.txt"
  12:  }
 


In opening the results of this file in a KIXtart script, the results were very sporadic, having weird characters, and never returned the expected data. By the way, The ‘Out-File’ in its current form above seems to have the same output effect as a regular DOS redirect command, within the Powershell environment: i.e: $VM > “\\server\share$\VMCount.txt”

Since there is no point in listing all the different things I have done, I will tell you exactly what the problem is in this scenario:

Out-File apparently does not, by default output text in ASCII encoding, and therefore, the resulting text is usually un-interpretable by other scripts. In order to fix this, a small modification to the Out-File command would be required, so line 11 would look like this:

$VM | Out-File - append "\\server\share$\VMCount.txt" -encoding ASCII

Adding this small addition to the Out-File resolved the problem of incorrect encoding. I spent about 3 hours trying to figure out why my redirection weren’t working until I found the solution. So hopefully this will help someone who is a PowerShell novice like me, who may face the same problem.

Print Friendly
Subscribe By Email for Updates.