Powershell send mail - powershell-2.0

I am having the following problem.
I have a powershell script to send me emails with log files attached.
The only problem is that I need only the log files that are not empty.
So i have tried to use this script:
If ((Get-content "Log.txt") -gt 0 ) {
$smtp.Send($msg)
echo "email sent"
} else {
echo "File is blank"
}
It seems that -gt 0 is not working for me.
No matter what I have tried powershell still sends me the empty logs.
So can you please show me where I am wrong?
I have tried this as well:
If ((Get-Content $file) -eq $Null) {
"File is blank"
} else {
$smtp.Send($msg)
echo "email sent"
}
But it is still not working.
Thank you in advance.

Get-Content will read the entire contents of the file - only to throw it all away! That's a huge waste of resources.
Instead, get info from the fileystem itself about the file with get-item or get-childitem.
if ((get-item "log.txt").length -gt 0) {
do stuff
}
It also looks like you're using an antiquated method of sending email. In PowerShell 2.0 and above, use Send-MailMessage - it's much easier to use. In fact, if you have all the logfiles in one directory, you can distill this to a two-liner:
$logs = get-childitem -path PATH_TO_LOGS|where-object{($_.length -gt 0) -and !$_.PSIsContainer}|select-object -expandproperty fullname
Send-Mailmessage -attachments $logs OTHER_PARAMETERS_HERE

Related

Initiate an email based on script output or console output in Jenkins

I have a script which basically fetches the http response codes. I want to trigger an email for response code anything apart from 200. I do not want to trigger mail using script. Is there any way to send a mail in post build actions ?
Kindly assist.
#!/bin/bash
date
if [ $# -eq 0 ]; then
cat /home/ubuntu/check_kibana/lists.txt | while read output
do
RESP=$(curl -sL $output -w "%{http_code} \n" -o /dev/null)
if [ $RESP -eq 200 ]; then
echo "ResponseCode: $RESP, Service is active."
else
echo "ResponseCode: $RESP, $output is not active."
echo "ResponseCode: $RESP for $output. Please check as the service may be down or not listening to the designated port." | mail -s "Error triggered for unavailable kibana service" xxxxxxxxx#gmail.com
fi
done
fi
If you are running this as a build step then you need to add exit 1; in the else part of the response code check. This will mark the build step as a failure and then you can set up an email trigger using "Email Notification" as a post-build step. In case, If you want to have personalized email then you can use "Editable Email Notification" plugin.
So, your script should be something like this
#!/bin/bash
date
if [ $# -eq 0 ]; then
cat /home/ubuntu/check_kibana/lists.txt | while read output
do
RESP=$(curl -sL $output -w "%{http_code} \n" -o /dev/null)
if [ $RESP -eq 200 ]; then
echo "ResponseCode: $RESP, Service is active."
else
exit 1; # Any exit code except 0 will mark the build step as the failure
echo "ResponseCode: $RESP, $output is not active."
echo "ResponseCode: $RESP for $output. Please check as the service may be down or not listening to the designated port." | mail -s "Error triggered for unavailable kibana service" pruthvi.basagodu#gmail.com
fi
done
fi
To fix the above issue, we need to know that Jenkins will trigger the email notification only if the build fails or changes from failure to success. (depends on how you want to trigger an email via Jenkins).
I have found a way to solve the above issue. Instead of shell script, python would be right choice for me me as it is very flexible to play around with the various libraries and variables. So, those who want to trigger an email based on the loop conditions in the script, go with python or any OOP languages.
Shell script will only run the script and sets the build status. If I am wrong, I'd be happy receive the suggestions.

Creating registry DWORD entry with PowerShell

I am trying to create registry entries for some time now.
Enviroment:
Offline environment (No Domain)
1 Windows Server 2012 R2
200 Windows 7 clients
The following entry should be created on several computers:
[HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system]
"LocalAccountTokenFilterPolicy"=dword:00000001
For this I would like to use the following script
$Computers = Get-Content "C:\Scripts\Clients.txt"
$Path = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System"
$Name = "LocalAccountTokenFilterPolicy"
$PropertyType = "DWord"
$Value = 1
$results = foreach ($computer in $Computers) {
if (Test-Connection -ComputerName $computer -Count 1 -Quiet) {
try {
Set-ItemProperty -Path $path -Name $Name -Value $Value -Type $PropertyType -ErrorAction 'Stop'
$status = "Success"
} catch {
$status = "Failed"
}
} else {
$status = "Unreachable"
}
New-Object -TypeName PSObject -Property #{
'Computer' = $computer
'Status' = $status
}
}
$results | Export-Csv -NoTypeInformation -Path "./error.csv"
The script is executed, no error appears, but the entries were not created.
Where is my error?
Always try a simple 'Get' first, and then progress to testing lines before trying your 'Set'...
So you first test locally on a system, before your foreach invoke, on single system:
`Get-ItemProperty HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name LocalAccountTokenFilterPolicy`
If you get a good response like this:
LocalAccountTokenFilterPolicy : 0
PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Curre
ntVersion\Policies\System
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\Curre
ntVersion\Policies
PSChildName : System
PSDrive : HKLM
PSProvider : Microsoft.PowerShell.Core\Registry
Then you've got the right command to work with. Now change the 'Get' to a 'Set' and work out the values LOCALLY.
I think you are close, but missed something in your tests...
Do ONE at a time, locally, first in PowerShell ISE. Then invoke-command to that same single system, then one by one add your tests...
- Patrick Burwell, 25 year Windows and Linux SysAdmin

send-mailmessage opens file instead of sending it

Can anyone tell me why this opens instead of sends the file?
$d = [DateTime]::Today.AddDays(-90)
Get-ADComputer -Filter 'lastLogon -le $d' -Properties lastLogon |
Export-Csv c:\temp\stale_servers.csv
If (c:\temp\stale_servers.csv = $?)
{
Send-MailMessage -SmtpServer xxxxxxxxx -To xxxxxxxxx -From xxxxxx -Subject "test mail" -Body "The servers that have not logged in, in the past 90 days are attached." -attachment c:\temp\stale_servers.csv
}
I think the issue is in this line:
If (c:\temp\stale_servers.csv = $?)
if you want to test the existence of the file use:
If (test-path -path "c:\temp\stale_servers.csv" )

How to use AppCMD to test and see if a website exists in IIS7 using the Site's Name?

I would like to add new bindings to a site using appcmd but I need to see if it exists first. How can I do so using AppCMD?
Much appreciated!
You can create a batch file with the following code :
#ECHO OFF
SET appcmd=CALL %WINDIR%\system32\inetsrv\appcmd
%appcmd% list site /name:"Default Web Site"
IF "%ERRORLEVEL%" EQU "0" (
ECHO EXISTS
REM Add your bindings here
) ELSE (
ECHO NOT EXISTS
)
Here's the PowerShell way:
$exists = (&$appcmd list apppool /name:'MyApplicationPool') -ne $null
if ($exists -eq $false)
{
Write-Host 'App Pool does not exist'
}
else
{
Write-Host 'App Pool exists'
}
You can specify the site.name and do that in one line with the command line : "%systemroot%\system32\inetsrv\AppCmd.exe" list apps /path:"/PORTALSiteName" /site.name:"Default Web Site" && ECHO EXISTS

Powershell debugging event -Action code block

I have script watching file creation in a specific directory.
I'm using Register-ObjectEvent after creating a System.IO.FileSystemWatcher,
It works great, but if I set a break point in the -Action code block the IDE generates a:
WARNING: Breakpoint Line breakpoint on 'D:\My Stuff\Desktop\scripts\fileWatcher.ps1:15' will not be hit
this message happens right after I drop a file into the directory I'm watching and I can see my Write-Host printing out my message right after the above 'warning'.
Is this normal?
I need to add more code and could really use the debugger..
What can\should I do, so I can debug this code block?
$fsw = [System.IO.FileSystemWatcher] $path
Register-ObjectEvent -InputObject $fsw –EventName Created -SourceIdentifier DDFileCreated -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp" -fore green
Out-File -FilePath $logFile -Append -InputObject "The file '$name' was $changeType at $timeStamp"
}
If you trigger the event from a direct powershell command in the same ISE or console session, it actually works:
$path = (Resolve-Path '~\').Path
if(Test-Path "$path\newfile.txt"){ del "$path\newfile.txt" }
$fsw = [System.IO.FileSystemWatcher] $path
Register-ObjectEvent -InputObject $fsw –EventName Created -SourceIdentifier DDFileCreated -Action {
$name = $Event.SourceEventArgs.Name # put breakpoint here, via ISE or script
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file '$name' was $changeType at $timeStamp" -fore green
}
'foo' | out-file "$path\newfile.txt" # breakpoint hit
But if you simply hook up the event and wait for some external process to create a file, I see the issue you are hitting.
So if you can add some test code to directly trigger your event, go with that.
If not, read on...
It seems like you cannot enter the debugger while the shell or ISE is waiting for a new command, you can only enter while another command is executing.
Going with that theory, this is the workaround (works for me):
Set your breakpoint
Run your event subscription code
Run the command "Read-Host" in the ISE console window, or from the prompt in the shell
Wait until you know your event should have fired due to external process
Hit "enter" to allow Read-Host to complete
Viola, breakpoint hit!
The real key is to have a loop running so the script never exits. Then debugging and breakpoints work.
E.g.
# At the end of the script.
while ($true) {
Start-Sleep -Seconds 1
}
More detail is here.

Resources