Category Archives: Powershell demo

How to Use PowerShell to Detect Logins and Alert Through Email using SendGrid

From Microsoft MSDN, The Get-WinEvent data from event logs that are generated by the Windows Event Log technology introduced in Windows Vista.And, events in log files generated by Event Tracing for Windows (ETW).By default, Get-WinEvent returns event information in the order of newest to oldest.

Get-winevent : Gets events from event logs and event tracing log files on local and remote computers. The Get-WinEvent cmdlet uses the LogName parameter to specify the Windows PowerShell event log. The event objects are stored in the $Event variable.

This script reads the event log “Microsoft-Windows-TerminalServices-LocalSessionManager/Operational” from servers and outputs the human-readable results to Mail. The -MaxEvents 1 Specifies the maximum number of events that are returned. Enter an integer such as 100. The default is to return all the events in the logs or files.

#################################################################
#Project : How to Use PowerShell to Detect Logins and Alert Through Email using SendGrid
#Developer : Thiyagu S (dotnet-helpers.com)
#Tools : PowerShell 5.1.15063.1155 
#E-Mail : mail2thiyaguji@gmail.com 
##################################################################

$Timestamp = [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date), 'India Standard Time')
$Text = "Timelines in IST"
$EmailBody = get-winevent -filterhashtable @{logname='Microsoft-Windows-TerminalServices-LocalSessionManager/Operational';id=21} -MaxEvents 1 | Format-List -Property TimeCreated,Message
$EmailFrom = "servermonitor@dotnet-helpers.com"
$EmailTo = "dotnet-helpers@accenture.com mail2thiyaguji@gmail.com"
$EmailSubject = "Server Login Notification"
$SMTPServer = "smtp.sendgrid.net"
[string][ValidateNotNullOrEmpty()] $Username = "azure_ad8e8e784erf789.com"
[string][ValidateNotNullOrEmpty()] $pwd = "xxxxxxxxxxx"
$pwd1 = ConvertTo-SecureString -String $pwd -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $Username, $pwd1
$SMTPPort = 587
Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $EmailSubject -body ($EmailBody + "($Text)" + "($Timestamp)" | Out-String) -SmtpServer $SMTPServer -Port $SMTPPort -Credential $cred 

The Windows Task Scheduler can automatically send email at a specific time or in response to a specific event. The below article will help to configure the script in Windows Scheduler Task

Here i setting this script to execute the script if any user log in to the server, so it will intimate to the supervisor by triggering mail. Go to Triggers tab and add a new trigger. The trigger should be set to fire at log on, which can be selected from the drop down.

OUTPUT:

Creating HTML report with CSS (Cascading Style Sheet) using Powershell

All Tech/non Tech peoples loves a nice HTML report for reviewing. Creating these type of reports in PowerShell is very easy and simple. These type of nice HTML reports can be generate with the help ConvertTo-HTML cmdlet. Converts Microsoft .NET Framework objects into HTML that can be displayed in a Web browser. The ConvertTo-HTML does not create an actual file, just the HTML code.This means that we can modify the HTML on the fly and save the file when finished. 

For this simple report i had used only few properties like -CssUri , -Postcontent and -PreContent from the ConvertTo-HTML cmdlet.

Pre/Post Content

Usually we will create table and generate content with the help of ConvertTo-HTML cmdlet. But if you want to insert additional HTML directives to put in before and after the main code. This can be achieve using “-PreContent” and “-PostContent” cmdlet.

-PreContent : Specifies text to add before the starting tag. By default, there is no text in that position

-PostContent : Specifies text to add after the closing tag. By default, there is no text in that position

CssUri

Specifies the Uniform Resource Identifier (URI) of the cascading style sheet (CSS) that is applied to the HTML file. The URI is included in a style sheet link in the output.

Final code:

Here i had wrote the required CSS code for the report and placed the below code in notepad and saved with the name C:\dotnet-helpers\design.css. The same CSS will be called during the report generation. So the style will be applied to the final HTML report.

body { background-color:#E5E4E2;
font-family:Monospace;
font-size:10pt; }
table,td, th { border:1px solid black;}
th { color:#00008B;
background-color:white; 
font-size: 12pt;}

table { margin-left:30px; }
h2 {
font-family:Tahoma;
color:#6D7B8D;
}
h1{color:#DC143C;}
h5{color:#DC143C;}

In the below script I’m adding style from an external CSS file with help of -CssUri parameter (-CssUri ‘C:\temp\design.css’) and generating the HTML report in the destination location. The CSS from the file will applied to the HTML element during the execution and generate the report as like below.

Get-Eventlog -List | Select @{Name="Logs";Expression = {$_.LogDisplayname}} , 
@{Name="Entries";Expression = {"{0:n0}" -f $_.entries.count}} |
#Converts Microsoft .NET Framework objects into HTML that can be displayed in a Web browser.
#the Title, Body, PreContent, and PostContent parameters of ConvertTo-Html to customize the output..
convertto-html -Title "Daily Log Report" -PreContent "<H1>Daily Event Log Report : $($env:COMPUTERNAME)</H1>" -PostContent "<H5><i>Copy right @ dotnet-helpers.com</i></H5>" -CssUri 'C:\dotnet-helpers\design.css' |
Set-Content C:\dotnet-helpers\DailyLogReport.htm

Output:

How To Display GUI POP UP message box in PowerShell

One of the simplest way to build simple message boxes in PowerShell is to “borrow” from .NET COM objects. Basically you initialize the object, and then you need to create instances of the object and finally call the Popup method. These messagebox code may be familiar to anyone who has programmed in vbScript, or any of the Microsoft programming languages such as Visual Basic or C#. The boxes can look pretty good, even though the coding is a bit monster.

In simple, all it really takes is two lines. One line to create the Wscript.Shell COM object and one to invoke the Popup method. Before the execution, let we discuss about the syntax below

Syntax :

intButton = objShell.Popup(strText,[nSecondsToWait],[strTitle],[nType])

Parameters :

strText String value containing the text you want to appear
in the pop-up message box.
nSecondsToWait It’s an optional. Maximum length of time to display the pop-up message
box (in seconds, Optional, default=infinite)
strTitle Title text string, It’s an optional.
nType Type of buttons and icons (Numeric, Optional)
These determine how the message box is used.

Button Types : OK = 1, Cancel = 2, Abort = 3, Retry = 4, Ignore = 5,                         Yes = 6, No = 7

Icon Types : 16  – “Stop Mark” icon. ,  32 – “Question Mark” icon, 48 – “Exclamation Mark” icon.  , 64 – “Information Mark” icon.

 

The command will write the return value of the clicked button to the pipeline as shown below

Button the return value :1 – OK button ,2 -Cancel button , 3 – Abort button , 4 – Retry button ,5  – Ignore button  , 6 – Yes button  , 7 –  No button

Example #1:

#creating object os WScript
$wshell = New-Object -ComObject Wscript.Shell -ErrorAction Stop
#invoking the POP method using object
$wshell.Popup("Are you want to continue from here?",5,"Hello User?",48+4)

Script Explanation:

From the syntax, please find parameter values.

strText : Are you want to continue from here?
nSecondsToWait : 5 (wait for 5 second)
strTitle : Hello User?
nType : 48+4 (Exclamation Mark icon + Yes and No buttons)
IntButton : Get the selected input as show in below table

OUTPUT:

What do you think?

I hope you have an idea of  How to display a pop-up message box with PowerShell. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.

Create Shortcuts on Desktops using Powershell

Mostly we will simply copy an already created shortcut but With PowerShell you can create a shortcut by using the New-Object cmdlet. Let we look in to this detail below. Here’s a quick script to create a shortcut to Notepad and put it on the desktop.

Step #1: The First step is to define the location and name of your shortcut. The following example will add the shortcut to the user’s desktop with a name of Your Shortcut.

$SourceFileLocation = “$env:SystemRoot\System32\notepad.exe”
$ShortcutLocation = “C:\Users\thiyagu.a.selvaraj\Desktop\Notepad.lnk”

Step #2: The second step is to create a variable referencing a Wscript.Shell COM Object.

$WScriptShell = New-Object -ComObject WScript.Shell

Step #3: The third step is to add the target path to the method

$Shortcut = $WScriptShell.CreateShortcut($ShortcutLocation)
$Shortcut.TargetPath = $SourceFileLocation

Step #4: The final step is to envoke the Save() method to save your shortcut.

$Shortcut.Save()

Final Code

# Create a Shortcut with Windows PowerShell
$SourceFileLocation = "$env:SystemRoot\System32\notepad.exe"
$ShortcutLocation = "C:\Users\thiyagu.a.selvaraj\Desktop\Notepad.lnk"
#New-Object : Creates an instance of a Microsoft .NET Framework or COM object.
#-ComObject WScript.Shell: This creates an instance of the COM object that represents the WScript.Shell for invoke CreateShortCut
$WScriptShell = New-Object -ComObject WScript.Shell
$Shortcut = $WScriptShell.CreateShortcut($ShortcutLocation)
$Shortcut.TargetPath = $SourceFileLocation
#Save the Shortcut to the TargetPath
$Shortcut.Save()

 

What do you think?

I hope you have an idea of  how to create the Create Shortcuts on Desktops using Powershell. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.

Viewing Your Drive Information with PowerShell – Part 1

Managing drives, monitoring space to ensure that a drive run out of available capacity and to understanding just how many drives are on a single system this are simply able to monitor using PowerShell instead of manual monitoring. WMI – Windows Management Instrumentation can be a wealth of information that anyone should be able to query to get pretty much whatever  information they need.

#Look at only local drives
Get-WmiObject -Class Win32_logicaldisk -Filter "DriveType = '3'"
DeviceID : C:
DriveType : 3
ProviderName : 
FreeSpace : 35938738176
Size : 127509983232
VolumeName : OSDisk

In this post, we going to discuss about very simple query to get the Drive information. You can run the below query using the Get-WMIObject cmdlet to get more information about all of the drives on your system. From the above output, you can able to see that we have the DeviceID, which is the drive letter assigned to the drive; the FreeSpace, which is measured in bytes, as well as the capacity (size) of the drive; along with the volume name that has been specified.

Using the above information you can able to easily filter using the query for only drives that matched a certain type and while viewing the size in bytes is necessary to keep the size at the lowest possible level, sometimes it is nice to see it in a more  readable format, such as in GB like below, The property is specified by a hash table with two keys, Label and Expression.The name of the property is assigned to the Label key. The calculation is assigned to the Expression key.

Get-WmiObject -Class Win32_logicaldisk -Filter "DriveType = '3'" | 
Select-Object -Property DeviceID, DriveType, VolumeName, 
@{Label='FreeSpaceGB';E={"{0:N2}" -f ($_.FreeSpace /1GB)}},
@{Label="Capacity";E={"{0:N2}" -f ($_.Size/1GB)}}

OUTPUT:

what is dot-sourcing in Powershell

Dot-sourcing is a concept in PowerShell that allows you to reference code defined in one script.

When you writing large size of PowerShell scripts, then there always seems to come a time when a single script just isn’t enough.  If we working on large size of script then it important to keep your scripts Simple and Reusable, so you can keep your block of script as modular. The Dot-sourcing is a way to do just that. Making script as modular it also useful when requirment came for adding some more functionlaiyt in exting script. Other than building a module, dot-sourcing is a better way to make that code in another script available to you.

For example, let’s say I’ve got a script that has two functions in it. We’ll call this script CommunicateUser.ps1. Here i had created single module which contain the two functionality in single file which used for sending email and SMS to the customer.

CommunicateUser.ps1

function SendEmail {
param($EmailContent)
#Write your Logic here 
Write-Output "****************************************"
Write-Output "Sending Mail" $EmailContent
Write-Output "****************************************"
}`
function SentSMS {
param($SMSContent)
#Write your Logic here 
Write-Output "****************************************"
Write-Output "Sending SMS" $SMSContent
Write-Output "****************************************"
}

Now i had created another script called UpdateUser.ps1. Here we needs to invoke those functions for sending the information to user. The CommunicateUser.ps1 script is located on the root of my C drive, so we can just put a period followed by a space and then the path of the script like shown below.

UpdateUser.ps1

# My CommunicateUser.ps1 script were located on the root of my C drive, so I just put a period, followed by a space and then the path of the script.
. C:\Users\MYPC\Desktop\PowerShell\CommunicateUser.ps1
$mailContent = 'MAIL - Hi Welcome to dotnet-helpers.com'
$smsContent = 'SMS - Hi Welcome to dotnet-helpers.com'
# Method Name (SendEmail) Parameter Name (-EmailContent) Parameter Value ($mailContent)
SendEmail -EmailContent $mailContent
SentSMS -SMSContent $smsContent

To make those functions available in the same scope, let we invoked CommunicateUser.ps1 script now, so now SendEmail and SentSMS are now available in the scope for use.  To dot source a script is very simple. I’ll now dot source my functions script inside of my CommunicateUser.ps1 script.

OUTPUT:

 

What do you think?

I hope you have an idea of how to utilize the dot-sourcing concept in Powershell. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.

Application Pool Monitoring Automation – Powershell to check if an application pool has stopped

Monitoring the App pool status manually is very difficult for all the time, and some times we may aware that App pool has stopped while browsing the URL so to avoid those type of scenario below PowerShell script will help of check the status of the application pool recycle and start if its stopped. So you can make integrate the below script in Task scheduler for specific interval time for checking the status of the App pool and start if it stopped. You may also include the email trigger if its stopped and started by the script.

Executed and Tested Version

OS : Windows 10
IIS : 10.0.15063.0
PowerShell version : 5.1.15063.1155

# Load IIS module:
Import-Module WebAdministration

# SET AppPool Name
$AppPoolName = "DefaultAppPool"

#Testing if a String is NULL or EMPTY.
if ([string]::IsNullOrWhiteSpace($AppPoolName))
{
Write-Output "$AppPoolName does not exist"
}
else 
{
try {
#Determines whether all elements of a file or directory path exist.
if (Test-Path IIS:\AppPools\$AppPoolName){
# Start App Pool if stopped else restart
#Get the runtime state of the DefaultAppPool and checking the status
if ((Get-WebAppPoolState($AppPoolName)).Value -eq "Stopped"){
Write-Output "Starting IIS app pool"
#starting the App Pool
Start-WebAppPool $AppPoolName
}
else {
Write-Output "Application pool is Running successfully"
}
}
}
catch {
Write-Output $_.Exception.Message
throw
} 

}

 

What do you think?

I hope you have idea of how to check the application pool status and start using Powershell . I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.

How to move files from one location to another location using PowerShell

In this article, Let me show you how to move files from one location to another location using PowerShell script. The Move-Item cmdlet moves an item, including its properties, contents, and child items, from one location to another location. The locations must be supported by the same provider.

Move-Item : Cannot create a file when that file already exists.

Example:1 Moving single files/folders

In the PowerShell window, type the command below and press ENTER. After the –path parameter, type the path of the file on your local PC that you want to copy, and after the –destination parameter, type the path of the destination folder. In the example below, I’m moving a file called URL_List.txt from the Source File Path folder to the Destination File Path folder.

$_SourcePath = "D:\BLOG\Power Shell\Examples\Source File Path\URL_List.txt"
$_DestinationPath = "D:\BLOG\Power Shell\Examples\Destination File Path"

Move-item –path $_SourcePath –destination $_DestinationPath

OR we can directly mention the path of files location without -path Keyword

Move-item $_SourcePath $_DestinationPath

Example:2 Moving all the item which created today.

From below code, we getting all files and folder which created today and move from “Source File Path” folder to “Destination File Path” folder.

get-childitem -Path "D:\BLOG\Power Shell\Examples\Source File Path" -Recurse |
Where-Object {$_.CreationTime -gt (Get-date).Date} |
move-item -destination "D:\BLOG\Power Shell\Examples\Destination File Path"

Also, by default, Get-ChildItem does not move hidden files. To move hidden files, use the Force parameter with Get-ChildItem.

Example:3 Moving the files based on File Type (extension)

I had created $_FileType array which contains the list of file types that need to move. After execution, all .html and .txt files will move from source to destination folder. Please refer to the snapshots to under stand the before and after the script execution

#location of starting directory
$_sourcePath ="C:\Users\dotnet-helpers\Desktop\SourcePath"
#location where files will be copied to 
$_destinationPath = "C:\Users\dotnet-helpers\Desktop\DestinationPath";
#Array of extension that need to move from source path
$_FileType= @("*html*", "*.*txt")

Get-ChildItem -recurse ($_sourcePath) -include ($_FileType) | move-Item -Destination ($_destinationPath)

OUTPUT:

Before Execution: Source Folder/Destination Folder

After Execution: Source Folder/Destination Folder

 

What do you think?

I hope you have an idea of how to move the files from one location to another location using the Powershell script. I would like to have feedback from the readers of my posts. Your valuable feedback, question, or comments about this article are always welcome.

 

How to check response code from a website using PowerShell

In this post we will discuss about how to check the response code from a website. In this article, we’re going to cover how to build a PowerShell function that will query a specific URL and attempt to find out if that URL is working fine or not. To get started, let’s construct a function for this task called CheckSiteURLStatus with a single parameter called URL.

Net.WebReques makes a request to a Uniform Resource Identifier (URI). This is an abstract class.

Using Net.WebRequest class (which is under the System.Net namespace), we get a response from a web server. Unlike the Net.WebClient class, you will not be able to download the site page. However, using Net.WebRequest class, you can get a response code and also see what type of web server is being used to host the site. The WebRequest class has a static method called Create in which we can pass a URL to invoke a HTTP,  We’ll add the code to create the request into our function as shown below.

[string] $_URL = 'https://dotnet-helpers.com'
function CheckSiteURLStatus($_URL) {
try {
$request= [System.Net.WebRequest]::Create($_URL)
$response = $request.getResponse()
if ($response.StatusCode -eq "200") {
write-host "`nSite - $_URL is up (Return code: $($response.StatusCode) - 
$([int] $response.StatusCode)) `n" -ForegroundColor green 
}
else {
write-host "`n Site - $_URL is down `n" ` -ForegroundColor red
}
} catch {
write-host "`n Site is not accessable, May DNS issue. Try again.`n" ` -ForegroundColor red
}
}

CheckSiteURLStatus $_URL

Based on the response code, the condition will execute and write on the console.Finally, we’ll need to dispose of the response after we’re done to clear it from memory which would finish it off to make it look like this:

OUTPUT

What do you think?

I hope you have idea of how to check the Website status using Powershell script. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.

 

Difference between write-host and write-output in powershell

One of the great benefits of PowerShell is its pipeline mechanics that enable the output of one command to be passed to the next command in the pipeline. That output is not sent as basic text but rather the actual objects generated from a command are sent in the native object format to the next command and this is enabled for all commands.

Example: 1

If you open a PowerShell window and type the following commands the result is the same for both, Let us test this by the below cmdlet.

PS C:\> Write-Host ("Hello " + $env:USERNAME)
Hello Aadharsh

PS C:\> Write-Output ("Hello " + $env:USERNAME)
Hello Aadharsh

If we look at the above script, it like they are the same but in reality, they are working in very different ways. Let us discuss more to understand this more.

Example: 2

From Example 1, we think that it seemed to achieve the same result for both Write-Output and Write-Host but we have differences between these two cmdlets. This can be demonstrated in more detail in this example. Write-Output sends the output to the pipeline. From there it can be piped to another cmdlet or assigned to a variable. Write-Host sends it directly to the console

$a = 'Testing Write-OutPut' | Write-Output
$b = 'Testing Write-Host' | Write-Host

Get-Variable a,b

From the above example, we can able see the Write-Output cmdlet has passed the value to the next process but Write-Host just directly writes to the host and nothing has to send forward to the next cmdlet. 

In simpler, if you possibly want to write data to the screen, but also want the data to be passed down the pipeline to further commands, then use Write-Output.  Write-Host does not output data to PowerShell Object flow Engine but rather, as the name implies, writes directly to the host and sends nothing to the PowerShell engine to be forwarded to commands later in the pipeline.