Beau D'Amore
Beau D'Amore

Reputation: 3392

access $args/params from inside method

I am working on an error handling method for my PowerShell scripts. I pass it the error via try/catch on the catch, but I want to iterate through the original params from the command line that called it in order to create an error log and error email.

Here's what I have so 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 for debug
$paramList = $args

# --functions--

function Handle-MyError
{
  Write-Host "handle-error"
  Write-Host $args[0];  # this is the 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
  for ($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 my try/catch:

catch [Exception]
{
  Write-Host "SPOT 1"
  Handle-MyError $_.
}

At the top, I try to save the original $args as $paramList to loop through later, but it's not working. Inside the Handle-MyError method, $args becomes the error that is passed so I thought if I save the original $argsas $paramList I could access it later, but it's wonky... Ideas?

Upvotes: 1

Views: 256

Answers (2)

Beau D'Amore
Beau D'Amore

Reputation: 3392

Here's my final code after some help from @beatcracker. I combined two pieces of the puzzle.

  1. I need to save the initial params in a local var and Two, ($paramList = $PsBoundParameters)
  2. Access this var/list using .GetEnumerator()

    # --params--
    param(
        [string]$Directory,
        [string]$ArchiveDirectory,
        [string]$ErrorDirectory,
        [string]$ErrorEmailFrom,
        [string]$ErrorEmailTo,
        [string]$ErrorEmailSubject,
        [string]$ErrorSMTP,
        [string]$FTPSite,
        [string]$FTPUser,
        [string]$FTPPass,
        [string]$FTPRemoteDir
    )
    # set params as var for debug later
    $paramList = $PsBoundParameters
    
    # --functions--
    
    function Handle-MyError
    {
        Write-Host "handle-error"
        #write-host "Exception:" $args[0];  # this is the exception passed in
    
        # -Email alert-
    
        # build subject
        $subject = $ErrorEmailSubject + " " + $FTPSite 
    
        # build message
        $message =  Get-Date -format s
        $message += "`r`nError Message: " + $args[0]
        $message += "`r`nParameters:`r`n" 
    
        $paramList.GetEnumerator() | ForEach-Object `
        {
            #Write-Host $_.Key "=" $_.Value
            if ($_.Key -ne "FTPPass"){
                $message += "`r`n" + $_
            }
        }
    }
    

Upvotes: 0

beatcracker
beatcracker

Reputation: 6920

There are several ways, in order of worst to best:

Use Get-Variable with Scope parameter. Scope number can differ, but it should be at 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 for 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 $_
}

Upvotes: 3

Related Questions