0

I have a script to manage hyper-v virtual machines. When I execute the command to shut down a machine, I need the warning to be saved in the log if it is shut down.

The script I have only captures the errors, I need to get both errors and warnings:

Try {
    Stop-VM $Machine -ErrorAction Stop
} Catch {
    Write-Host "Error: $_"
    Add-Content -Path $Log -Value "`n$_"
}

Thanks!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
khilian
  • 3
  • 2
  • 2
    Add `$WarningPreference = 'Stop'` at the top of your script or use `-WarningAction Stop`, this way warnings will be treated as terminating error. – Santiago Squarzon Jun 25 '21 at 23:37
  • 2
    You can even throw in a `-WarningVariable Warning`, and evaluate against that with an `if` statement: `if($Warning){ add-content -value $Warning`. Could do the same for errors – Abraham Zinala Jun 25 '21 at 23:41

1 Answers1

2

Assuming that Stop-VM issues non-terminating errors:

Stop-VM $Machine *> output.log

Note: This redirects all of PowerShell's output streams to file output.log, including success output, if any, and it would work with passing an array of VM names in $Machine.

As Abraham Zinala points out, you can selectively capture (some of the) output streams, in variables, using the the common -WarningVariable parameter as well as -ErrorVariable, which you can later send to a file as needed. Note that using these variables still produces the original stream output, but you can silence that with -WarningAction SilentlyContinue and -ErrorAction SilentlyContinue. See the answer linked below for details.


As Santiago Squarzon points out, you could extend your original approach by adding -WarningAction Stop, but the limitation, as explained in this answer, is that only the first error or warning emitted by the call is then captured, and, perhaps more importantly, the command is terminated at that point - even if multiple VMs were specified.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 1
    Understood, @SantiagoSquarzon, but the - perhaps not obvious (amended a bit now) - point of my answer is that you don't need a loop for cmdlets that have _array_-valued parameters: they typically emit _non_-terminating errors and warnings, which a redirection / use of `-*Variable` common parameters can _all_ capture. – mklement0 Jun 26 '21 at 00:22