access $args/params from inside method - powershell

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?

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 $_
}

Here's my final code after some help from #beatcracker.
I combined two pieces of the puzzle.
I need to save the initial params in a local var and Two, ($paramList = $PsBoundParameters)
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" + $_
}
}
}

Related

Send confirmation message if command ran with Invoke-Expression completes successfully

I'm writing a PowerShell script to add / remove people from a distribution group. I want to send a message if the action was successful and another if it failed. This is part of the script:
foreach ($x in Get-Content $pathfile\inputfile.txt) {
$USER = $x.Split(',')[0]
$ACTION = $x.Split(',')[1]
$COMMAND = (Write-Output "$ACTION-DistributionGroupMember -Identity 'Group Name' -Member $USER")
if ($ACTION -ieq "remove") {
$COMMAND = $COMMAND + ' -Confirm:$false'
Invoke-Expression $COMMAND
}
else {
Invoke-Expression $COMMAND
}
}
inputfile.txt, for the sake of information is:
jdoe#example.com,Add
jsmith#example.com,Remove
I've tried using $? and $lasExitCode but neither of those worked as expected as they only consider the output of "Invoke-Expression" and that is always successful.
What I am expecting is:
foreach ($x in Get-Content $pathfile\inputfile.txt) {
$USER = $x.Split(',')[0]
$ACTION = $x.Split(',')[1]
$COMMAND = (Write-Output "$ACTION-DistributionGroupMember -Identity 'Group Name' -Member $USER")
if ($ACTION -ieq "remove") {
$COMMAND = $COMMAND + ' -Confirm:$false'
Invoke-Expression $COMMAND
#if $COMMAND successful: Write-Output "$ACTION on $USER succeeded."
#if $COMMAND unsuccessful: Write-Output "$ACTION on $USER failed."
}
else {
Invoke-Expression $COMMAND
#if $COMMAND successful: Write-Output "$ACTION on $USER succeeded."
#if $COMMAND unsuccessful: Write-Output "$ACTION on $USER failed."
}
}
$? won't work because even if the command fails, Invoke-Expression was invoked successfully.
Use the & call operator to invoke the call directly instead, and $? will work. For the conditional parameter argument, use splatting!
foreach ($x in Get-Content $pathfile\inputfile.txt) {
$user,$action,$null = $x.Split(',')
# construct command name
$command = "$ACTION-DistributionGroupMember"
# organize the parameter arguments in a hashtable for splatting later
$paramArgs = #{
Identity = 'Group Name'
Member = $USER
}
# conditionally add the `-Confirm` parameter
if ($ACTION -ieq "remove") {
$paramArgs['Confirm'] = $false
}
# invoke the command with the call operator
& $command #paramArgs
if($?){
# command invocation suceeded
}
else {
# command invocation failed
}
}

PowerShell: Working with the error from Standard Out (using Nessus Essentials)

Trying to use PowerShell to capture the running status of the "Nessus Essentials" software product. Simply trying to capture product status: running, not running, or other. Getting the below error each time. I've tried changing -like to -match and changing string [warn] [scanner] Not linked to a manager to various other shorter versions, with wildcards and without, to no avail. I still get several lines of an ugly error message when all I want is one line with the string Not linked to a manager returned to console with nothing beneath that.
Pertinent snippet working incorrectly:
} elseif(($agentStatus.stdOut -like "[warn] [scanner] Not linked to a manager")) {
Throw "Not linked to a manager"
The Error:
The Code:
Function Start-ProcessGetStreams {
[CmdLetBinding()]
Param(
[System.IO.FileInfo]$FilePath,
[string[]]$ArgumentList
)
$pInfo = New-Object System.Diagnostics.ProcessStartInfo
$pInfo.FileName = $FilePath
$pInfo.Arguments = $ArgumentList
$pInfo.RedirectStandardError = $true
$pInfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pInfo.CreateNoWindow = $true
$pInfo.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden
$proc = New-Object System.Diagnostics.Process
$proc.StartInfo = $pInfo
Write-Verbose "Starting $FilePath"
$proc.Start() | Out-Null
Write-Verbose "Waiting for $($FilePath.BaseName) to complete"
$proc.WaitForExit()
$stdOut = $proc.StandardOutput.ReadToEnd()
$stdErr = $proc.StandardError.ReadToEnd()
$exitCode = $proc.ExitCode
Write-Verbose "Standard Output: $stdOut"
Write-Verbose "Standard Error: $stdErr"
Write-Verbose "Exit Code: $exitCode"
[PSCustomObject]#{
"StdOut" = $stdOut
"Stderr" = $stdErr
"ExitCode" = $exitCode
}
}
Function Get-NessusStatsFromStdOut {
Param(
[string]$stdOut
)
$stats = New-Object System.Collections.Hashtable
$StdOut -split "`r`n" | % {
if($_ -like "*:*") {
$result = $_ -split ":"
$stats.add(($result[0].Trim() -replace "[^A-Za-z0-9]","_").ToLower(),$result[1].Trim())
}
}
Return $stats
}
Function Get-DateFromEpochSeconds {
Param(
[int]$seconds
)
$utcTime = (Get-Date 01.01.1970)+([System.TimeSpan]::fromseconds($seconds))
Return Get-Date $utcTime.ToLocalTime() -Format "yyyy-MM-dd HH:mm:ss"
}
Try {
$nessusExe = Join-Path $env:ProgramFiles -ChildPath "Tenable\Nessus\nessuscli.exe" -ErrorAction Stop
} Catch {
Throw "Cannot find NessusCli.exe"
}
Write-Host "Getting Agent Status..."
$agentStatus = Start-ProcessGetStreams -FilePath $nessusExe -ArgumentList "managed status"
If($agentStatus.stdOut -eq "" -and $agentStatus.StdErr -eq "") {
Throw "No Data Returned from NessusCli"
} elseif($agentStatus.StdOut -eq "" -and $agentStatus.StdErr -ne "") {
Throw "StdErr: $($agentStatus.StdErr)"
} elseif(($agentStatus.stdOut -like "[warn] [scanner] Not linked to a manager")) {
Throw "Not linked to a manager"
} elseif(-not($agentStatus.stdOut -like "*Running: *")) {
Throw "StdOut: $($agentStatus.StdOut)"
} else {
$stats = Get-NessusStatsFromStdOut -stdOut $agentStatus.StdOut
If($stats.last_connection_attempt -as [int]) { $stats.last_connection_attempt = Get-DateFromEpochSeconds $stats.last_connection_attempt }
If($stats.last_connect -as [int]) { $stats.last_connect = Get-DateFromEpochSeconds $stats.last_connect }
If($stats.last_scanned -as [int]) { $stats.last_connect = Get-DateFromEpochSeconds $stats.last_scanned }
}
$stats | Out-Host
Note: Code above is courtesy of here, I've only made a change to the path of Nessus, and I am adding the attempt to capture that it's not connected to a manager.
Modify your code so that it separates standard output from error and so that it handles each line separately.
The following is how to capture standard output (excluding else statements and error handling) of a program (according to your $Proc variable)
if ($proc.Start())
{
while (!$proc.StandardOutput.EndOfStream)
{
$StreamLine = $proc.StandardOutput.ReadLine()
if (![string]::IsNullOrEmpty($StreamLine))
{
# TODO: Duplicate code in this scope as needed or rewrite to use multiline regex
$WantedLine = [regex]::Match($StreamLine, "(?<wanted>.*Not linked to a manager.*)")
$Capture = $WantedLine.Groups["wanted"]
if ($Capture.Success)
{
Write-Output $Capture.Value
}
}
}
}
After that deal with error output separately:
$StandardError = $Proc.StandardError.ReadToEnd()
if (![string]::IsNullOrEmpty($StandardError))
{
# Or use Write-Error
Write-Output $StandardError
}

Trying to understand a PowerShell function

I'm brand new to PowerShell and am working on modifying a script to combine 4 functions into one. I am having a little trouble understanding how all the pieces of the individual functions fit together. For example, it has a $msg variable that doesn't seem to be declared anywhere else in the script. So essentially i'm looking for any advice on how to make these fit.
##LogSuccess function
##Display provided message as a SUCCESS in green, with SUCCESS: prefix
##If logging mode is set to true, also write SUCCESS message to $logfileSS
Function global:LogSuccess($msg){
Write-Host "SUCCESS: " $msg -ForegroundColor "Green"
$timestamp = Get-Date
$msg = $timestamp.ToString() + ": " + $msg
if ($global:loggingmode){
Write-Output "SUCCESS: " $msg | Out-File -filepath $global:logfile -Append
}
}
##LogError function
##Display provided message as an error in red, with ERROR: prefix
##If logging mode is set to true, also write ERROR message to $logfile
Function global:LogError($msg){
Write-Host "ERROR: " $msg -ForegroundColor "Red"
$timestamp = Get-Date
$msg = $timestamp.ToString() + ": " + $msg
if ($global:loggingmode){
Write-Output "ERROR: " $msg | Out-File -filepath $global:logfile -Append
}
}
##LogWarning function
##Display provided message as a WARNING in yellow, with WARNING: prefix
##If logging mode is set to true, also write WARNING message to $logfile
Function global:LogWarning($msg){
Write-Host "WARNING: " $msg -ForegroundColor "Yellow"
$timestamp = Get-Date
$msg = $timestamp.ToString() + ": " + $msg
if ($global:loggingmode){
Write-Output "WARNING: " $msg | Out-File -filepath $global:logfile -Append
}
}
##Logging function
##Display provided message as a general information message in cyan
##If logging mode is set to true, also write information message to $logfile
Function global:Logging($msg){
Write-Host $msg -ForegroundColor "Cyan"
$timestamp = Get-Date
$msg = $timestamp.ToString() + ": " + $msg
if ($global:loggingmode){
Write-Output $msg | Out-File -filepath $global:logfile -Append
}
}
from my point of view those functions are not designed as intended, e.g.:
Function global:Logging($msg){
Write-Host $msg -ForegroundColor "Cyan"
$timestamp = Get-Date
$msg = $timestamp.ToString() + ": " + $msg
if ($global:loggingmode){
Write-Output $msg | Out-File -filepath $global:logfile -Append
}
}
PowersShell functions accept named input parameters and are outputting objects in general. In simple words this is the concept. Currently those functions do not return objects they do update/use variables with the scope global. This is a dangerous approach and not needed.
About scopes: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes?view=powershell-7.2
About functions: https://learn.microsoft.com/en-us/powershell/scripting/learn/ps101/09-functions?view=powershell-7.2
Back to the one example you should do something like this:
Function write-LogFile {
<#
.Description
Enter your description here
.Parameter Message
Enter your description of the parameter here
.Parameter LogToTextFile
Enter the desscription of the parameter here
.Parameter Path
Enter the desscription of the parameter here
.Example
Enter example calls here
#>
param (
[parameter(Mandatory=$true,Position=1)]
[ValidateNotNullOrEmpty()]
[string]$Message,
[parameter(Mandatory=$true,Position=2)]
[switch]$LogToTextFile,
[parameter(Mandatory=$true,Position=3)]
[ValidateNotNullOrEmpty()]
[string]$Path
)
Begin {
}
Process {
try {
Write-Host $msg -ForegroundColor "Cyan"
$timestamp = Get-Date
$msg = $timestamp.ToString() + ": " + $msg
if ($LogToTextFile){
Write-Output $msg | Out-File -filepath $path -Append
}
Else {
$msg
}
}
Catch {
write-error $_
}
}
End{
}
}
So I think before you start to merge those function you need first to understand the concept how to write a function. The provided links should help you to find the right path...

What can I change in this script to prevent an infinite loop

Here is my Powershell code that when i execute it, it will continually loop while waking up my internal sites
$urlFile = "C:\Users\lfouche\Desktop\url\url.txt"
foreach($site in Get-Content $urlFile){
function WakeUp([string] $url)
{
Write-Host "Waking up $url ..." -NoNewLine
$client = new-object system.net.WebClient
$client.UseDefaultCredentials = $true
$null = $client.OpenRead($url)
$client.Dispose()
Write-Host " Ok"
}
#(
Get-Content $urlFile
) | % { WakeUp $_ }
}
Well, your script can generally be improved, however I think the error is that you already iterate over Get-Content $urlFile within your foreach condition and also in the loop. Try this:
# define the wake up function once
function WakeUp
{
Param
(
[string] $url
)
Write-Host "Waking up $url ..." -NoNewLine
$client = new-object system.net.WebClient
$client.UseDefaultCredentials = $true
$null = $client.OpenRead($url)
$client.Dispose()
Write-Host " Ok"
}
$urlFile = "C:\Users\lfouche\Desktop\url\url.txt"
$sites = Get-Content $urlFile
foreach($site in $sites)
{
# call wake up for each site
WakeUp $site
}

sql failed jobs export to csv with powershell

I am battling with a PowerShell script that captures all SQL Failed jobs for the past day and exports it to .CSV
Please view code below.
param (
#[string]$serverInstance = '03RNB-VSQLPRD4\SQLPRD04
)
begin {
[void][reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
}
process {
try {
Write-Verbose "List failed SQL Server jobs using SMO..."
$serverInstance = Get-Content "C:\MountSpaceCollector\SQLJobFailures\servers2.txt";
$server = new-object Microsoft.SqlServer.Management.Smo.server $serverInstance
$results = #()
$reasons = #()
$jobs = $server.jobserver.jobs | where-object {$_.isenabled}
# Process all SQL Agent Jobs looking for failed jobs based on the last run outcome
foreach ($job in $jobs) {
[int]$outcome = 0
[string]$reason = ""
# Did the job fail completely?
if ($job.LastRunOutcome -eq "Failed") {
$outcome++
$reasons += "Job failed: " + $job.name + " Result: " + $job.LastRunOutcome
# Did any of the steps fail?
foreach ($jobStep in $job.jobsteps) {
if ($jobStep.LastRunOutcome -ne "Succeeded") {
$outcome++
$reasons += "Step failed: " + $jobStep.name + " Result: " + $jobStep.LastRunOutcome
}
}
}
if ($outcome -gt 0) {
$jobFailure = New-Object -TypeName PSObject -Property #{
Name = $job.name
LastRunDate = $job.lastrundate
LastRunOutcome = $reasons
}
$results += $jobFailure
}
}
Write-Output $results | Export-CSV -Path 'C:\MountSpaceCollector\SQLJobFailures\SQLJobFailures.csv' -Delimiter '|'
}
catch [Exception] {
Write-Error $Error[0]
$err = $_.Exception
while ( $err.InnerException ) {
$err = $err.InnerException
Write-Output $err.Message
Write-Output $results
}
}
}
But It Exports all except the last field (LastRunOutcome). It only displays "System.Object[]"?
Can anyone please assist with this as I do not know what I am doing wrong?
It's because $Reasons is an object, more specifically an array. You need to format the reasons differently, as a string for instance, to be able to have it appear in the CSV normally.
Perhaps you meant to use the string $Reason that you declare, but don't use?