mthiha207au
Contributor
Contributor

get-view command redirect error to logfile

I am unable to capture error to logfile of get-view unmount luns command. Usual way to redirecting using 2>&1 | tee -append $logfile or out-file wont work.

Here is an example:

$StorageSys = Get-View $VMHost.Extensiondata.ConfigManager.StorageSystem
$storagesys.UnmountVmfsVolume($invaliduuid) 2>&1 | Tee-Object -Append $logFile
$storagesys.UnmountVmfsVolume($invaliduuid) | outfile -append $logfile    #### Prefer Tee method as i need screen output too 
 
any workaround?
 
Thanks,
Max
0 Kudos
3 Replies
LucD
Leadership
Leadership

You could use a Try-Catch construct

$StorageSys = Get-View $VMHost.Extensiondata.ConfigManager.StorageSystem
try{
   $storagesys.UnmountVmfsVolume($invaliduuid)
}
catch{
   $Error[0] | Tee-Object -FilePath .\error.log -Append | Write-Error
}

The Write-Error in the Catch block is to get the error formatted as an error (in red by default)


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
mthiha207au
Contributor
Contributor

Thanks LucD. Try and catch works well in this case. 
I still have another problem with error redirection and will continue to discuss here. Please be patient as I am new to redirection.

 

Assuming $InvalidCluster is invalid. 

Get-Cluster $InvalidCluster 2>&1 | Tee-Object -FilePath .\error.log -Append  #This works fine and write error to screen and file

 

However, This doesnt work and I am confused. 

Get-Cluster $InvalidCluster | Remove-Cluster -confirm:$false 2>&1 | Tee-Object -FilePath .\error.log -Append #Write only to screen , not to file

 

Do I need Try-Catch? Its confusing why the latter is not working. 

 

 

0 Kudos
LucD
Leadership
Leadership

That is probably due to the PowerShell stream that is used for the error message.
If you merge redirect the output to the screen, there is nothing for the Tee-Object to act upon.

In any case, with the Try-Catch you only would get to the Remove-Cluster when the Get-CLuster does not cause an exception.
I would do

try {
   Get-Cluster $InvalidCluster -ErrorAction Stop | Remove-Cluster -confirm:$false 2>&1
}
catch {
  $Error[0] | Tee-Object -FilePath .\error.log -Append
}


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos