Capturing errors in this Powershell script - powershell

I have this test script to change the Administrator password on a list of servers.
I have set the script to log errors if the server can't be ping'd or account can't be found etc. However in addtion to this i'd like to capture any other errors that take place and also add those to the log file. I know you can use the "Try and Catch" for error handling but havn't had any luck so far.
Would someone be kind enough to show how to do it?
Here is the script
$date = Get-Date
$user = "Administrator"
$newpwd = "MyPassword"
$servers = gc C:\servers.txt
foreach ($server in $servers)
{
$ping = new-object System.Net.NetworkInformation.Ping
$Reply = $null
$Reply = $ping.send($server)
if($Reply.status -like 'Success')
{
$Admin=[adsi]("WinNT://" + $server + "/$user, user")
if($?)
{
$Admin.SetPassword($newpwd)
if($?)
{Add-Content -path C:\Audit\logs\servers-reset.csv -Value "$server, Succsess the $user password was changed. , $date"}
else
{Add-Content -path C:\Audit\logs\servers-reset.csv -Value "$server, Error: FAILED to change the password. , $date"}
}
else
{
Add-Content -path C:\Audit\logs\servers-reset.csv -Value "$server, Error: The $user user account was not found on the server. , $date"}
}
else
{
Add-Content -path C:\Audit\logs\servers-reset.csv -Value "$server, Error: Ping FAILED could not connect. , $date"
}

If you want to write exceptions to the log right after they were thrown, you could use a trap. Add something like this to you script:
trap [Exception] {
#Add message to log
Add-Content -Path test.csv -Value "$server, $($_.Exception.Message), $(Get-Date)"
#Continue script
continue;
}
That will log all exceptions (not all errors).
If you want all errors, you can access them using $Error. It's an arraylist containing every error during your sessions(script). The first item $Error[0] is the latest error. This however, is not something that fits directly into an csv file without formatting it.

Related

Sending email with CSV from a Running Process check

I'm trying to check if a process is running on a remote computer (Eventually will be about 100 computers). If the process is not running, I'd like it to put the computername/IP into a CSV and then email that out. If the process is running on all machines, I'd like the script to not send an email out at all. To do this, I'd like to test the machines first to check they're online (If they're offline, we've either got bigger problems or it's off for a reason, but that's not what this process is checking for.
I'm going to be testing this script on a few machines with just the notepad process at the moment as it's something I can do on a test machines reletively quickly.
I'm a little stuck at the moment, because I don't know how to get the results from the process check to be put into a CSV and then emailed. In the code snippet below, it's not generating the outfile, but have left the variable I was testing with and the path to where the attachment would be in the send-mailmessage. Any advice will be appreciated, I'm still learning powershell at the moment so don't know all the tricks and tips yet.
Cheers
# Mail server Configuration
$MailServer = "mail.server.co.uk"
$MailFrom = MailFrom#server.co.uk"
# Mail Content Configuration
$MailTo = "Recipient#Server.co.uk"
$MailSubjectFail = "INS Process not running on $DAU"
$MailBodyFail = "The INS Process on the DAU $DAU is not running. Please manually start process on DAU $DAU"
# Process Info
$Process = "Notepad"
$ProcessIsRunning = { Get-Process $Process -ErrorAction SilentlyContinue }
#Results Info
$Exportto = "C:\Scripts\Content\INSChecker\Results.csv"
# Get DAU Information
foreach($line in (Get-Content C:\Scripts\Content\INSChecker\INSList.cfg)){
$line = $line.split(",")
$DAU = $line[0]
$DAUIP = $line[1]
# Test Connection to INS DAU
write-host "Testing: $DAU / $DAUIP"
$TestDAU = Test-Connection $DAU -quiet
$TestDAUIP = Test-Connection $DAUIP -quiet
write-host "Tests: $TestDAU / $TestDAUIP"
If($TestDAU -ne 'True'){
If($TestDAUIP -ne 'True'){
write-host "DNS Not resolved for $DAU"
Write-Output "INS $DAU/$DAUIP is OFFLINE" | Out-File C:\Scripts\Content\INSChecker\INSProcessCheck.log -append
}
}
Else{
# Get Process Running State and Send Email
if(!$ProcessIsRunning.Invoke()) {
Send-MailMessage -To $MailTo -From $MailFrom -SmtpServer $MailServer -Subject $MailSubjectFail -Body $MailBodyFail -Attachments C:\Scripts\Content\INSChecker\Results.csv
} else {
"Running"
}
}
}
Hopefully this gives a you a hint on where to begin and how to approach the problem, I have removed the irrelevant parts of the script and only left the logic I would personally follow.
The result of $report should be an object[] (object array) which should be very easy to manipulate and very easy to export to CSV:
#($report).where({ $_.SendMail }) | Export-Csv $exportTo -NoTypeInformation
I'll leave you the remaining tasks (attach the CSV, send the emails, etc) for your own research and design.
$ErrorActionPreference = 'Stop'
# Process Info
$Process = "Notepad"
$ProcessIsRunning = {
param($computer, $process)
# On Windows PowerShell -ComputerName is an option,
# this was removed on PS Core
try
{
$null = Get-Process $process -ComputerName $computer
# If process is running return 'Running'
'Running'
}
catch
{
# else return 'Not Running'
'Not Running'
# send a Warning to the console to understand why did this
# fail ( couldn't connect or the process is not running? )
Write-Warning $_.Exception.Message
}
}
#Results Info
$ExportTo = "C:\Scripts\Content\INSChecker\Results.csv"
$exportProps = 'Server', 'IP', 'Ping', 'DNSResolution', 'Process', 'SendMail'
# Get DAU Information
$report = foreach($line in Get-Content path/to/file.txt)
{
$status = [ordered]#{} | Select-Object $exportProps
$DAU, $DAUIP = $line = $line.split(",")
$status.SendMail = $false
$status.Server = $DAU
$status.IP = $DAUIP
# Test ICMP Echo Request and DNS Resolution
$ping = Test-Connection $DAUIP -Quiet
$dns = Test-Connection $DAU -Quiet
$status.Ping = ('Failed', 'Success')[$ping]
$status.DNSResolution = ('Failed', 'Success')[$dns]
$status.Process = & $ProcessIsRunning -computer $DAUIP -process $Process
if(-not $ping -or -not $dns -or $status.Process -eq 'Not Running')
{
$status.SendMail = $true
}
[pscustomobject]$status
}
#($report).where({ $_.SendMail }) # => This is what should be mailed

How to Log Errors in Powershell?

[1] I am trying to create Error logs for my PowerShell script. I need to create a function so that instead of using Write-Host I can directly call that function and whatever the error I am getting in the Script can be directly logged into the Log File.
[2] I have used the following method but it doesn't seem that will work for every PowerShell script.
function WriteLog
{
Param ([string]$LogString)
$LogFile = "C:\$(gc env:computername).log"
$DateTime = "[{0:MM/dd/yy} {0:HH:mm:ss}]" -f (Get-Date)
$LogMessage = "$Datetime $LogString"
Add-content $LogFile -value $LogMessage
}
WriteLog "This is my log message"
[3] Can Anyone Suggest a more easy way to handle logging of Error into the file?
You are not far off for your use case.
You don't need Write-Host at all for this at all. Depending on what PS version you are using, Write-Host is not prudent when you are sending data down the pipe or elsewhere
Write-Host is just bad in legacy, pre-v5x versions if you were sending stuff in the pipeline because it cleared the buffer, so they'd be noting to send. In v5x
and higher. As per the founder/creator of Monad/PowerShell.
• Write-Host Harmful
https://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful/
https://devblogs.microsoft.com/scripting/understanding-streams-redirection-and-write-host-in-powershell
https://powershell.org/2012/06/how-to-use-write-host-without-endangering-puppies-or-a-manifesto-for-modularizing-powershell-scripts
PowerShell Best Practice #3: Avoid Write-Host
it now writes to the Information stream, as per the founder/creator of Monad/Powershell.
• However, this thought has been changed since the v5x stuff.
You can use direct logging using either
Tee-Object
Export-Csv -Append
Out-File -Append
... and other redirection options.
You can also, create and write to your own event log...
New-EventLog -LogName LogonScripts -Source ClientScripts
Write-EventLog LogonScripts -Source ClientScripts -Message 'Test Message' -EventId 1234 -EntryType Warning
...then read from it later as you would any other event log.
There are lots of examples (scripts and modules) all of the web to use as is and start with or tweak as needed, even the ones via the Microsoft powershellgallery.com.
ScriptLogger 2.0.0
Write-Log: A Simple Logging Function for your PowerShell - Scripts: Download - Write-Log.ps1:
Write-Log PowerShell Logging Function: Download - Function-Write-Log.ps1:
Logging 2.4.9
Point of note in your post. This...
$LogFile = "C:\$(gc env:computername).log"
... just simplify to this...
$LogFile = "C:\$($Env:COMPUTERNAME).log"
#set logfile-path on global scope
$Logfile = "C:\Temp\Logfile.log" # set your Logfile-Path here
function Write-Log {
param
(
[Parameter(ValueFromPipeline)]
[string]$content
)
$FileExists = Test-Path -Path $LogFile
$DateNow = Get-Date -Format 'dd.MM.yyyy HH:mm'
$FileInp = $DateNow + ' | ' + $content      
if ($FileExists -eq $True){
Add-Content -Path $LogFile -Value $FileInp 
}
else {
New-Item -Path $Logfile -ItemType file
Add-Content -Path $LogFile -Value $FileInp
}
}
#then you only have to pipe it to Write-log like this:
Write-Output "hello world" | Write-Log

Supress error in powershell and display custom error message

I have created a PowerShell script that will add a VPN connection for Cisco Meraki.
The script itself functions as intended, but if a error occures, the "Completed" popup appears, with the error message shown in the PS windows.
Is it possible to supress the error and show a custom error popup based on the error that appears, while stopping the "Completed" popup from appearing?
I am aware of the $ErrorActionPreference= 'silentlycontinue', but unsure of how to implement this with a custom error.
Script to add VPN connections for Cisco Meraki.
$Name = Read-Host -Prompt 'Enter the profile name for this VPN connection'
$password = Read-Host -assecurestring "Please enter your Pre-shared Key"
$password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
Add-VpnConnection -Name "$Name" -ServerAddress 193.214.153.2 -AuthenticationMethod MSChapv2 -L2tpPsk "$password" -TunnelType L2tp -RememberCredential -Force
$wshell = New-Object -ComObject Wscript.Shell
$wshell.Popup("VPN-profile for $Name has been created.
You may now use this connection.
Username and password is required on first time sign on.
Support: _witheld_ | _witheld_",0,"Completed")
Since your script continues to run after the error occurs, you are dealing with a non-terminating error, so you can use the -ErrorVariable common parameter to capture a given cmdlet invocation's error(s).
Using a simplified example, which you can apply analogously to your Add-VpnConnection call:
# Call Get-Item with a nonexistent path, which causes a *non-terminating* error.
# * Capture the error with -ErrorVariable in variable $err.
# * Suppress the error console output with -ErrorAction SilentlyContinue
Get-Item /NoSuch/Path -ErrorVariable err -ErrorAction SilentlyContinue
$null = (New-Object -ComObject Wscript.Shell).Popup(
$(if ($err) { "Error: $err" } else { 'Success.' })
)
If you were dealing with a terminating error, you'd have to use try / catch:
# Call Get-Item with an unsupported parameter, which causes a
# *(statement-)terminating* error.
try {
Get-Item -NoSuchParam
} catch {
# Save the error, which is a [System.Management.Automation.ErrorRecord]
# instance. To save just a the *message* (a string), use
# err = "$_"
$err = $_
}
$null = (New-Object -ComObject Wscript.Shell).Popup(
$(if ($err) { "Error: $err" } else { 'Success.' })
)
Note:
Neither -ErrorAction nor -ErrorVariable work with terminating errors.
Conversely, try / catch cannot be used to handle non-terminating errors, which is presumably why Ranadip Dutta's answer didn't work for you.
For a comprehensive discussion of PowerShell error handling, see this GitHub issue.
You have to have the error handling for the script. I have given it as a whole in the below script but you can configure it based on your need:
try
{
$Name = Read-Host -Prompt 'Enter the profile name for this VPN connection'
$password = Read-Host -assecurestring "Please enter your Pre-shared Key"
$password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))
Add-VpnConnection -Name "$Name" -ServerAddress 193.214.153.2 -AuthenticationMethod MSChapv2 -L2tpPsk "$password" -TunnelType L2tp -RememberCredential -Force
$wshell = New-Object -ComObject Wscript.Shell
$wshell.Popup("VPN-profile for $Name has been created.You may now use this connection.Username and password is required on first time sign on.Support: _witheld_ | _witheld_",0,"Completed")
}
catch
{
"Your custom message"
$_.Exception.Message
}
For further refence, read TRY/CATCH/FINALLY in Powershell
Hope it helps.

Speed Powershell Script Up

I am looking for way to speed up my Powershell script. I have a script that returns the manager Employee ID and manager name based on a .txt file that has the samaccountnames for each user under that manager. The problem is the list is very long, about 1400+ names and the script is taking forever to run. Here is my script. It works, just looking for a way to speed it up:
cls
If (!(Get-Module -Name activerolesmanagementshell -ErrorAction SilentlyContinue))
{
Import-Module activerolesmanagementshell
}
Write-host $("*" * 75)
Write-host "*"
Write-host "* Input file should contain just a list of samaccountnames - no header row."
Write-host "*"
Write-host $("*" * 75)
$File = Read-Host -Prompt "Please supply a file name"
If (!(test-path $File))
{
Write-host "Sorry couldn't find the file...buh bye`n`n"
exit
}
get-content $File | %{
$EmpInfo = get-qaduser -proxy -Identity $_ -IncludedProperties employeeid,edsva_SSCOOP_managerEmployeeID
# Check if we received back a Manager ID - if yes, get the Manager's name
# If not, set the Manager Name to "NONE" for output
If ($($EmpInfo.edsva_SSCOOP_managerEmployeeID).length -gt 2)
{
# Get the Manager's name from AD
$($EmpInfo.edsva_SSCOOP_managerEmployeeID)
$ManagerName = $(Get-QADUser -SearchAttributes #{employeeid=$($EmpInfo.edsva_SSCOOP_managerEmployeeID)} | select name).name
If (!$ManagerName)
{
$ManagerName = "NONE"
}
# Add the Manager name determined above (or NONE) to the properties we'll eventually output
$EmpInfo | Add-Member -MemberType NoteProperty -Name ManagerName -Value $ManagerName
}
Else
{
$EmpInfo.edsva_SSCOOP_managerEmployeeID = "NONE"
}
# Output user samaccountname edsva_SSCOOP_managerEmployeeID and ManagerName to a file
$EmpInfo | select samaccountname,edsva_SSCOOP_managerEmployeeID,ManagerName | export-csv "C:\Users\sfp01\Documents\Data_Deletion_Testing\Script_DisaUser_MgrEmpID\Disabled_Users_With_Manager.txt" -NoTypeInformation -Append
} # End of file processing loop
Ok, first things first... asking your user to type in a file name. Give them a nice friendly dialog box with little effort. Here's a function I keep on hand:
Function Get-FilePath{
[CmdletBinding()]
Param(
[String]$Filter = "All Files (*.*)|*.*|Comma Seperated Values (*.csv)|*.csv|Text Files (*.txt)|*.txt",
[String]$InitialDirectory = $home,
[String]$Title)
[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $InitialDirectory
$OpenFileDialog.filter = $Filter
$OpenFileDialog.Title = $Title
[void]$OpenFileDialog.ShowDialog()
$OpenFileDialog.filename
}
Then you can do:
$File = Get-FilePath -Filter 'Text Files (*.txt)|*.txt|All Files (*.*)|*.*' -InitialDirectory "$home\Desktop" -Title 'Select user list'
That doesn't speed things up, it's just a quality of life improvement.
Secondly, your 'can't find the file' message will appear as the window closes, so the person that ran your script probably won't see it. Towards that end I have a function that I use to pause a script with a message.
Function Invoke-Pause ($Text){
[reflection.assembly]::LoadWithPartialName('Windows.Forms')|out-null
If($psISE){
[Windows.Forms.MessageBox]::Show("$Text", "Script Paused", [Windows.Forms.MessageBoxButtons]"OK", [Windows.Forms.MessageBoxIcon]"Information") | ?{(!($_ -eq "OK"))}
}Else{
Write-Host $Text
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
}
With that you can get a message to the user, and then close the script so the user knows what happened. This function works in both the PowerShell console, as well as in the PowerShell ISE. In the console you get a text message that you define, and then a 'Press any key to continue...' message, and it waits for the user to press a key. In the ISE it pops up a window with your message, and waits for the user to click the OK button before proceeding. You could do something like:
If(!(Test-Path $File)){Invoke-Pause "Sorry couldn't find the file...buh bye";exit}
Now to get on to speeding things up!
You have more than one employee per manager right? So why look up the manager more than once? Setup a hashtable to keep track of your manager info, and then only look them up if you can't find them in the hashtable. Before your loop declare $Managers as a hashtable that just declares that 'NONE' = 'NONE', then inside the loop populate it as needed, and then reference it later.
Also, you are appending to a file for each user. That means PowerShell has to get a file lock on the file, write to it, close the file, and release the lock on it... over and over and over and over... Just pipe your users down the pipeline and write to the file once at the end.
Function Get-FilePath{
[CmdletBinding()]
Param(
[String]$Filter = "All Files (*.*)|*.*|Comma Seperated Values (*.csv)|*.csv|Text Files (*.txt)|*.txt",
[String]$InitialDirectory = $home,
[String]$Title)
[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $InitialDirectory
$OpenFileDialog.filter = $Filter
$OpenFileDialog.Title = $Title
[void]$OpenFileDialog.ShowDialog()
$OpenFileDialog.filename
}
cls
If (!(Get-Module -Name activerolesmanagementshell -ErrorAction SilentlyContinue))
{
Import-Module activerolesmanagementshell
}
Write-host $("*" * 75)
Write-host "*"
Write-host "* Input file should contain just a list of samaccountnames - no header row."
Write-host "*"
Write-host $("*" * 75)
$File = Get-FilePath -Filter 'Text Files (*.txt)|*.txt|All Files (*.*)|*.*' -InitialDirectory "$home\Desktop" -Title 'Select user list'
If (!(test-path $File))
{
Write-host "Sorry couldn't find the file...buh bye`n`n"
exit
}
$Managers = #{'NONE'='NONE'}
Get-Content $File | %{
$EmpInfo = get-qaduser -proxy -Identity $_ -IncludedProperties employeeid,edsva_SSCOOP_managerEmployeeID
Switch($EmpInfo.edsva_SSCOOP_managerEmployeeID){
{$_.Length -lt 2} {$EmpInfo.edsva_SSCOOP_managerEmployeeID = 'NONE'}
{$_ -notin $Managers.Keys} {
$MgrLookup = Get-QADUser -SearchAttributes #{employeeid=$EmpInfo.edsva_SSCOOP_managerEmployeeID} |% Name
If(!$MgrLookup){$MgrLookup = 'NONE'}
$Managers.add($EmpInfo.edsva_SSCOOP_managerEmployeeID,$MgrLookup)
}
}
Add-Member -InputObject $EmpInfo -NotePropertyName 'ManagerName' -NotePropertyValue $Managers[$EmpInfo.edsva_SSCOOP_managerEmployeeID] -PassThru
} | select samaccountname,edsva_SSCOOP_managerEmployeeID,ManagerName | Export-Csv "C:\Users\sfp01\Documents\Data_Deletion_Testing\Script_DisaUser_MgrEmpID\Disabled_Users_With_Manager.txt" -NoTypeInformation -Append

Out-file issues

I have this script
ForEach ($u in $usersFromFile)
{
try{
$nomailbox = if (-not (get-mailbox $u.alias)){
$notfound = $notfound + $nomailbox
Write-host "No mailbox for "$u.alias -F blue|out-file "d:\scripts\nomailbox.txt"}
}
Catch{}
Nothing is written to the outfile
What am I missing?
TIA
Andy
If you are using PowerShell version lower than 5, Out-Host writes to host, just like PetSerAl said, you should use Write-Output, instead. With PS 5 you can use Out-Host to achieve what previously couldn't be achieved with Out-Host.
Just use:
ForEach ($u in $usersFromFile) { try{
$nomailbox = if (-not (get-mailbox $u.alias)){
$notfound = $notfound + $nomailbox
Write-Output "No mailbox for "$u.alias -F blue|out-file "d:\scripts\nomailbox.txt"}
}
Catch{}
This should work. But i think, youre not gonna color this line without a reason.. You can use this with a function too:
function writehosttofile {
Param(
[switch]$para
)
Write-Host "No mailbox for "$u.alias -F blue
if($para){
"No mailbox for " + $u.alias
}
}
writehosttofile -para | out-file "d:\scripts\nomailbox.txt"
Write-Host
DESCRIPTION
Write-Host sends the objects to the host. It does not return any objects.
You can also browse to your script and redirect all output in a file:
PS C:\temp> cd c:\bin
PS C:\bin> .\script.ps1 > C:\bin\script_output.txt
have a nice day.