Hi,
I am struggling to understand a problem with a script that I am writing to shutdown our vSphere & NetApp infrastructure when our UPS battery is critical. If someone would be so kind as to assist in where I am going wrong I would appreciate it.
One function connects to vSphere, gets a list of running VMs and outputs this to a csv file. The value of the csv path is then returned by the function to be used elsewhere in the script.
The problem I am encountering is that the output of the connect-viserver command is being prepended to the returned data, and so I don't have a clean filename to a csv anymore. When I put a breakpoint on the return line, the value of $RunningVM_File is: C:\Path\To\file.txt, continue the script, and check the value of the variable the function is returned to, and returned value has changed to:
Name Port User
---- ---- ----
vCenter_Server_NAme 443 Domain\Username
C:\Path\To\file.txt
Here is the function causing the problem:
function Initialize-vSphereShutdown
{
[CmdletBinding()]
[OutputType([string])]
Param
(
# Param1 help description
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
$vSphereServer,
# Param2 help description
[string]
$BasePath,
[pscredential]
$Credential,
# Param help description
[Parameter(Mandatory=$true)]
[string]$Logfile
)
Begin
{
#Connect to vSphere
Connect-VIServer -Server $vSphereServer -Credential $Credential #-User $UserName -Password $Password
Write-Debug "Connected to: $vSphereServer"
Write-output ((Get-Date –f o) +" - Connected to vCenter / ESXi host: " + $vSphereServer) | out-file $Logfile -Append
$RunningVM_File = ($BasePath) +"RunningVMs.txt"
}
Process
{
if (Test-Path($RunningVM_File)){
Remove-Item($RunningVM_File)
}
#Return list of all ESXi hosts managed by connected host/vCenter
$ESXiSRV = Get-VMHost | Select-Object -ExpandProperty Name | Out-String
Write-Debug "The following ESXi hosts are available:"
Write-Debug $ESXiSRV
Write-output ((Get-Date –f o) +" - The following ESXi hosts are available: " + $ESXiSRV) | out-file $Logfile -Append
$vCenterESXiHost = Get-VMHost -VM $vSphereServer | Select-Object -ExpandProperty Name | Out-String
$vCenterESXiHost | Out-File ($BasePath + "vCenterESXiHost.txt")
Write-Debug "vCenter Server running on Host: $vCenterESXiHost"
Write-output ((Get-Date –f o) +" - vCenter Server running on Host: " + $vCenterESXiHost) | out-file $Logfile -Append
Write-Debug "Getting running VMs"
$RunningVM = Get-VM | Where-Object {$_.Powerstate -eq "Poweredon"} | select Name,Folder,VApp
$RunningVM | Export-Csv $RunningVM_File -NoTypeInformation
Write-Debug "List of running VMs saved to: $RunningVM_File"
Write-output ((Get-Date –f o) +" - List of running VMs saved to:" + $RunningVM_File) | out-file $Logfile -Append
}
End
{
return $RunningVM_File
}
}