powershell - access $args/params from inside method -


i working on error handling method powershell scripts. pass error via try/catch on catch, want iterate through original params command line called in order create error log , error email.

here's have far:

# --params-- param(   [string]$directory,   [string]$archivedirectory,   [string]$errordirectory,   [string]$erroremailfrom,   [string]$erroremailto,   [string]$erroremailsubject,   [string]$errorsmtp,   [string]$ftpsite,   [string]$ftpuser,   [string]$ftppass,   [string]$ftpremotedir )  # list of arguments debug $paramlist = $args  # --functions--  function handle-myerror {   write-host "handle-error"   write-host $args[0];  # exception passed in    # -email alert-   $subject = $erroremailsubject + $ftpsite    # build message   $message =  get-date -format "yyyy-mm-dd hh:mm:ss"    $message += "`r`nerror: " + $ftpsite + " : " + $args[0]   $message += "`r`nparameters:`r`n"     # grab each parameter value, using get-variable   ($i=0;$i -lt $paramlist.length; $i++)   {     $message += $paramlist[$i]   }    # send email   $smtp = new-object net.mail.smtpclient($errorsmtp)   $smtp.send($erroremailfrom, $erroremailto, $subject, $message)    # drop error file   $thedate = get-date -format "yyyymmdd"   $errorfile = $errordirectory + "\" + $thedate + "_error.txt"   write-host $errorfile   $message | out-file $errorfile -append } 

and in try/catch:

catch [exception] {   write-host "spot 1"   handle-myerror $_. } 

at top, try save original $args $paramlist loop through later, it's not working. inside handle-myerror method, $args becomes error passed thought if save original $argsas $paramlist access later, it's wonky... ideas?

there several ways, in order of worst best:

use get-variable scope parameter. scope number can differ, should @ least 2 (script->catch->handle-myerror)

function handle-myerror {    write-host (get-variable -name erroremailfrom -valueonly -scope 2) } 

using $script: prefix

function handle-myerror {    write-host $script:erroremailfrom } 

using $psboundparameters

# list of arguments debug $paramlist = $psboundparameters  function handle-myerror {    param    (        $exception,        $cfg    )     write-host $cfg.erroremailfrom }  catch [exception] {     write-host "spot 1"     handle-myerror -exception $_ -cfg $paramlist } 

using splatting:

$paramlist = $psboundparameters  function handle-myerror {     param     (         $exception,         $errordirectory,         $erroremailfrom,         $erroremailto,         $erroremailsubject,         $errorsmtp     )      write-host $erroremailfrom }  catch [exception] {     write-host "spot 1"     handle-myerror @paramlist -exception $_ } 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -