Output $error[0] Variable to Readable Format

Hi All,

I’ve got a script that runs reports against a vCenter server. It will tell me whether the VM exists or not. Everything works great except for the error var. I’m trying to output the $error I have below into a CSV file so that it’s easy to remove the characters before and after the single quotation marks. In the example below ‘testing’ is the VM that I can’t run a report against since it doesn’t exist in vCenter. I’m running this command to generate the output but I’d like it cleaned up a bit.

$error[0] | Group-Object | Format-Table Name -AutoSize | Out-String

Here is the output:

7/23/2020 2:10:42 PM Get-VM VM with name ‘testing’ was not found using the …

The date and time will change in each row that gets populated in the CSV file as the report is generated against the VM’s.

Any ideas would be appreciated!




Jim, welcome to Powershell.org. Please take a moment and read the very first post on top of the list of this forum: Read Me Before Posting! You’ll be Glad You Did!.

When you post code, error messages, sample data or console output format it as code, please.
In the “Text” view you can use the code tags “PRE“, in the “Visual” view you can use the format template “Preformatted“. You can go back edit your post and fix the formatting – you don’t have to create a new one.
Thanks in advance

There are several problems with the approach. $Error is all errors, not specifically a vm not being found, using the index 0 is just the last error that occurred. Not sure what the Group-Object is doing, but there should just be the last error and nothing to really group. Format-Table should be the end of pipeline. A better approach is to capture the error in a try catch:

try {
    $vm = Get-VM -Name $vmName -ErrorAction Stop
catch {
    'Error occurred connecting to VM {0}.{1}' -f $vmName, $_

There is a error e-book in the Resources section that you may want to take a look at as well