Powersheel script to fetch logs from remote desktop - powershell

We are working on one application and for that application there is one module called replicator and this replicator shows the status whether failed or successful in every h hrs it runs. So, I want to create a powershell script which will check the logs from my remote desktop server and email me the status of replicator .
Can somebody help me in this.

Are the logs in a text file? Does it have a particular format? Something like:
$logline = Get-Content \\path\to\file.txt -Last 1
Send-MailMessage -smtpserver smtp0 -from me#me.com -to me#me.com -Subject "Latest Result is $logline"

Related

Is there a way to execute a command from within a string or have more than one body in a powershell email?

I'm trying to send an email that contains both some information that I type out as well as the contents of a text file that was generated in earlier code. I was wondering if there is a convenient way of doing so without sending two emails? The code below didn't work but I can get the message to send if I only have the text or only have the contents of the txt file. Thanks!
Send-MailMessage -SMTPServer localhost -To myemail#email.com -From myemail#email.com -Subject "TESTING Active Domain Replication Failure TESTING" -Body "The following Domain Controller has had a replication failure. Please see attached txt files for more information. `n"(Get-Content -Path .\causeOfFailure.txt | out-string) -attachment error.zip
So I edited the statement to look like this:
$fileContent = (Get-Content -Path .\causeOfFailure.txt)
compress-archive -Path causeOfFailure.txt,dnsInformation.txt -update -DestinationPath error.zip
Send-MailMessage -SMTPServer localhost -To email#email.com -From email#email.com -Subject "TESTING Active Domain Replication Failure TESTING" -Body "The following Domain Controller has had a replication failure. Please see attached txt files for more information. `n & $ExecutionContext.InvokeCommand.ExpandString($fileContent)" -attachment error.zip
The output in the email shows this message
"System.Management.Automation.EngineIntrinsics.InvokeCommand.ExpandString(Source Controller:".
Is there a better way to have a string followed by a function both be part of the body of an email with the send-mailmessage command?
If you are trying to add the contents of a file to the body of the email, you can simply use $() to include functions within the quotes.
Send-MailMessage -SMTPServer localhost -To email#email.com -From email#email.com -Subject "TESTING Active Domain Replication Failure TESTING" -Body "The following Domain Controller has had a replication failure. Please see attached txt files for more information. `n $fileContent" -attachment error.zip
If you want to include the function within your script, you can do this,
Send-MailMessage -SMTPServer localhost -To email#email.com -From email#email.com -Subject "TESTING Active Domain Replication Failure TESTING" -Body "The following Domain Controller has had a replication failure. Please see attached txt files for more information. `n $(Get-Content -Path .\causeOfFailure.txt)" -attachment error.zip
The problem is because of the way you are constructing the body string.
You already have the content of the causeOfFailure.txt in a variable $fileContent, so there is no need to do a Get-Content on the same file again.
I would suggest you create your body in a separate variable first, to make the code more readable.
There are several options for this, like
Make use of a Here-String
$body = #"
The following Domain Controller has had a replication failure. Please see attached txt files for more information.
$fileContent
"#
Or insert a NewLine followed by the $fileContent using the -f Format operator
$body = 'The following Domain Controller has had a replication failure. Please see attached txt files for more information.{0}{1}' -f
[Environment]::NewLine, $fileContent
Or simply create as one double-quoted string
$body = "The following Domain Controller has had a replication failure. Please see attached txt files for more information.`r`n$fileContent"
Whichever you find is the most readable/maintainable method for your code.
Then for the part where you use the Send-MailMessage cmdlet.
Here again, writing out all parameters as one long line can make the code less readable and by doing that, mistakes are easily made.
There is a better way to use a cmdlet with lots of parameters, known as Splatting.
Applied to your code, this looks like:
# create a hashtable object with all parameters you want to use for Send-MailMessage
$mailParams = #{
SMTPServer = 'localhost'
To = 'myemail#email.com'
From = 'myemail#email.com'
Subject = "TESTING Active Domain Replication Failure TESTING"
Body = $body
Attachments = 'error.zip'
}
Send-MailMessage #mailParams
Hope this helps

Read time stamp from notepad using batch script

I'm looking solution for below issue :
We reload our application everyday and it will create the log file on daily.
sometimes the log stop writing because of some issues related to CPU usage and other strange stuff.
Now we want to monitor the log file on every 5 mins, if anything doesn't get updated in the log file then it should trigger an email.
The log file keep updating every 1 min, when the reload of file goes smooth.
I need read time stamp in the log file.The log file has time stamp column , it will write content in the log file in every 5 mins. so i need to read the time stamp inside the file for every 5 mins , if anything doesn't return more then 5 mins then i should trigger alert.
Is there any way to implement the above scenario using batch script or power shell or any other idea's to monitor log file is welcome.
Thanks for the help.
You definately can use Powershell for this purpose!
Make sure you have changed Powershell Execution Policy for scripts. You can change it like this:
Set-ExecutionPolicy -ExecutionPolicy Unrestricted
Here's the simple script that would handle it. It could be made as one/two liners of course, but i tried to make it to be more readable/understandable, there:
$FilePath = 'C:\log.txt' #Log file location
$Minutes = 5 #LastWriteTime older than 5 minutes from current time.
#General email parameters
$SMTP = 'your.smtp.server.local'
$From = 'yourserviceaccount#contoso.com'
$To = 'someperson#contoso.com'
$Subject = 'Action Required'
$Body = 'Log file havent been written from more than {0} minutes!' -f $Minutes
$LastWriteTime = (Get-ItemProperty -LiteralPath $FilePath).LastWriteTime
if ($LastWriteTime -ge (Get-Date).AddMinutes(-$Minutes))
{
Send-MailMessage -SmtpServer $SMTP -Port 25 -From $From -To $To -Subject $Subject -Body $Body -Priority High
}
You could then make a Scheduled Task that will trigger the script file every N-minutes.

PowerShell script for System state backups of domain controller not working

Hello I am trying to get an automated backup for my domain controller to a network share using a script and windows task scheduler - our domain controller is windows server 2008r2
this is the code for the script i have written as seen below, however when i run the scrip it does create the folder on the network share but fails to initiate the system state backup power shell returns this error when i run the script.
any suggestions on what i can do to resolve this issue? i am also rather new to powershell so there many be a much easier way of going about it.
many thanks
Gordon
wbadmin 1.0 - Backup command-line tool
(C) Copyright 2004 Microsoft Corp.
ERROR - One of the parameters or options specified is invalid: [quiet].
See the syntax below.
Syntax: WBADMIN START SYSTEMSTATEBACKUP
-backupTarget:<VolumeName>
[-quiet]
Description: Creates a system state backup of the local computer and stores
it on the location specified.
To use this command, you must be a member of the Backup Operators group
or Administrators group.
Parameters:
-backupTarget Specifies the location where you want to store the backup.
The storage location requires a drive letter or a GUID-based
volume of the format: \\?\Volume{GUID}.
-quiet Runs the command with no prompts to the user.
Example:
WBADMIN START SYSTEMSTATEBACKUP -backupTarget:f:
#adds windows server backup powershell snapin
Add-Pssnapin windows.serverbackup
#gets date
$date = Get-Date -Format dd.MM.yyyy
#declares backup location and adds date
$backdir = ("\\backupserver\bpdbackups\DC\$date")
#makes backup directory on network share
mkdir $backdir | out-null
#runs system statebackup
wbadmin start systemstatebackup -backupTarget:$backdir -[quiet]
#sends and email at the nd of the process
$smtp = "192.168.xxx.xxx"
$from = "Domain Controller <support#domain.com>"
$to = "Network Admin <network.helpxxx#xxx.com>"
$body = "The backup operation has been successfully done! Date: $date"
$subject = "Backup on $date"
#Send an Email to User
send-MailMessage -SmtpServer $smtp -From $from -To $to -Subject $subject -Body $body - BodyAsHtml
write-host "Backup Successful"
OK so you have a couple of problems here. Firstly square brackets around a command line switch indicates that it is optional and should not be included. Secondly I think you need to enclose the string variable since you are not calling a powershell applet.
Try changing:
wbadmin start systemstatebackup -backupTarget:$backdir -[quiet]
to
wbadmin start systemstatebackup -backupTarget:"$backdir" -quiet

Running Powershell script from batch - Send-MailMessage not functioning

I am facing unusual issue with Powershell script. I have written script to run DB queries which runs one STORED Procedure. Below is the complete script:
$server="DBServer,Inst"
$Database = "DATABASE"
$ConnectionTimeout = 30
$QueryTimeout = 120
$Query="STORED_PROCEDURE"
Import-Module “sqlps” -DisableNameChecking
$ds=Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $server -ConnectionTimeout $ConnectionTimeout -QueryTimeout $QueryTimeout
$date=(Get-Date).ToString()
$ret=$ds.Return
--Query returns 0 or 1, 0 means SP Passed otherwise failed.
$From="abc#xyz.com"
$SendCC= "aabbcc.b#xyz.com"
If ($ret -eq '0')
{
$Body=" STORED_PROCEDURE: <FONT COLOR=#00FF00> <b>PASS </b> </FONT> in <b> $server</b>:<i>$Database</i>; TimeStamp: $date"
$msg="Test: STORED_PROCEDURE - SUCCESS "
Write-Host "Sending Mail Notification - Ret 0"|
Send-MailMessage -From $From -To $SendCC -Subject $msg ($Body |Out-String) -BodyAsHtml -SmtpServer mail.xyz.com
Write-Host "Notification Sent!!"
}
This script works absolutely fine from my computer which is in xyz domain. I have created batch file to run this script as:
#pushd "D:\Temp\SM_SP"
powershell -ExecutionPolicy Bypass -File .\SP_SM.ps1 -noconsole
#popd
Even this batch file works fine in my computer, sends mail.. Works as expected! But the real issue is running the same in one of the test server (win Ser 2008 R2). Where the batch file when executed manually returns no errors – however I am not getting any mail notification.
Note-
• I have mentioned proper smtp server details in script, as I said the same script and batch are working fine in my computer which is in the same domain as this server.
• I have tested Powershell inbuilt command “Send-MailMessage” in the server as:
Send-MailMessage -From $from -To $to -Subject Test -SmtpServer mail.xyz.com
Where $from and $to both are my address and am receiving the mail absolutely fine. But in the server when I execute the above script in Powershell console or through wrapped Batch file – am not receiving mail.
Any help on this is greatly appreciated. Thanks in advance!
Regards
-Raaj
I've run into this issue several times as a result of Receive Connector settings in Exchange. We typically will just add the IP of a server to allow it to relay if we are going to start using it for sending email, otherwise we want connections refused.
If you're using exchange go to Server Configuration->Hub Transport and check what you have listed under "Receive mail from remote servers that have these IP addresses" on the Network tab. If you're using some other mail server I'd refer to the documentation on connection permissions for it. Also, if you're using a different user account on the server than you are using on your desktop you may want to try a Run as different user and see if it's something with the permissions of the account you're using on the server.

How to execute an external console application with PowerShell and send the result to email?

I need to execute some periodic console applications that give me some results (on the console)... How can I execute it and have its return data sent to my email?
I tried to use [Diagnostics.Process]::Start() and it launches my application but i don't know how to get the return... I do not want the exitCode, I want the text that the application prints on screen.
Using PS V2 CTP3.
*** UPDATE
The solutions presented worked fine but i have a problem... this application that i need to execute is gfix from the firebird database and now i discovered a thing, I can't redirect the output of gfix to a file, if i execute on command prompt the line:
gfix.exe -v -f dabatase.gdb > c:\test.txt
it print the output on the screen and the file is empty.
Same thing if I try to assign it to a variable... I don't know what difference gfix has from the other console apps that I use, but looks like its output can't be redirected.
Has someone seeing this?
*** UPDATE 2
Even if I use Start-transcript /Stop-Transcript, although on the screen I see the gfix output, on the file there is only the commands :/
*** UPDATE 3
Found the solution here
http://edn.embarcadero.com/br/article/25605
Something like this could work:
# temporary file
$f = [io.path]::GetTempFileName()
# start process and redirect its output to the temp file
ping localhost > $f
# create and send email
$emailFrom = "user#yourdomain.com"
$emailTo = "user#yourdomain.com"
$subject = "results"
$body = (Get-Content $f) -join "`r`n"
$smtpServer = "your smtp server"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)
# delete the file
remove-item $f
I think in this case [Diagnostics.Process]::Start() is not needed. Besides that there is a cmdlet Start-Process that does almost the same.
PowerShell v2 is now out, so you could consider upgrading.
Then, you can simply try:
PS > [string]$ipconfig=ipconfig
PS > send-mailmessage -to some_email -from from_email -subject PowerShell -body $ipconfig -bodyashtml -smtp my_smtp_server
Now, it depends on how complicated your command-line output is, because the above method will collapse multiple lines into a single on.