All posts by Thiyagu

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.

Simple function for error logging in PowerShell script

When writing larger scripts, logging is a must, so in this post I will share a simple function for logging PowerShell script. PowerShell scripts can easily be written without any kind of help content, documentation, commenting, or logging. Functionally, these scripts will sometimes work just fine, but what happens it failed in some case? You soon find yourself pulling your hair out trying to troubleshoot and debug this script in the most inefficient way possible. So logging the error is the best practice to handle the huge script.

One way to build in some kind of monitoring and troubleshooting assistance is through logging.

#This creates a log file with a date and time stamp
$logfile = "C:\EMS\dotnet-helpersErrorLog_$(get-date -format `"yyyyMMdd_hhmmsstt`").txt"
#this is our logging function, it must appear above the code where you are trying to use it.
function logger($val1 , $val2)
{
try
{
echo $val1 $val2
if ($val1 -eq 'Fail')
{ 
"Wrong Input passed so it was logged as error" + $val1 | out-file -Filepath $logfile -append
}
}
catch
{
$_.Exception.Message | out-file -Filepath $logfile -append
}
}

#Calling Logger function and passing parameters
logger 'Dotnet-helpers.com','Pass'
logger 'Dotnet-helpers.eu','Fail'

OUTPUT

 

What do you think?

I hope you have an idea of how to create simple log files for handling the issue. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.

Talking Through PowerShell

For this article, I would encourage you to un-mute your speakers and keep them at a reasonable level,or use headphones in case you are going through this in a public area or at work so you do not bother your neighbors.

Which scenario SPEAK class will required?

IF when you have a script that’s going to run a long time, say 10-20 minutes. We all KNOW that we’re not going to sit there and watch the output!. In this scenario, PowerShell talk when some condition comes up and its is really useful if you’ve relegated the window to the background and
are doing something else like working with other items.

Example of Real Scenario:

In below sample code the script will start to check the 10 lakhs record for finding the detail of specific user. If it match with user id it start specking with user details, so it will be make aware of the details by informaging through voice, if we working with other items.

#Loop through 1000000 users
foreach ($userId in $ListOfUsers)
{
if ($userId -eq '1456')
{
write-host "Got the User details"
write-host $userId
$speak.speakAsync("We found the User $($userId.FirstName) $($userId.LastName)")
}

Example: 1

The first thing that we want to do is create our SpeechSynthesizer object and then we can utilize the methods in it. During the execution of below script, the speak method talk which mentioned in the double quotes ie., “Hello from dotnet-helpers”.

ADD-TYPE -AssemblyName System.Speech
$speak = new-object System.Speech.Synthesis.SpeechSynthesizer
$speak.speakAsync("Hello from dotnet-helpers!")
$speak.Speak("The current date and time is $(Get-Date)")

If you wanted to increase the volume of the voice, you can adjust the Volume property from 0-100 on your object.You can even control the rate at which the words are spoken to you.

$speak.Volume = 100

If you want a faster response, you can also increase the rate to something like 10 using “Rate”.

Speed it up!

$speak.Rate = 10
$speak.speakAsync(“Hello from powershell!”)

Slow it down!

$speak.Rate = -10
$speak.speakAsync(“Hello from powershell!”)

What do you think?

I hope you have an idea of how to use the PowerShell SpeechSynthesizer during our long time execution for the output.  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.

Create custom name self signed certificate using PowerShell

During one of my client requirement, we received request for creating self-signed SSL certificate on IIS server for their play ground environment. so after  analyzing i had found it can be achievable using the New-SelfSignedCertificate cmdlet  which creates a self-signed certificate and its mainly using for testing purposes. Using the CloneCert parameter, a test certificate can be created based on an existing certificate with all settings copied from the original certificate except for the public key. The cmdlet creates a new key of the same algorithm and length.

In Manual, we need follow many steps to create the self signed certificate in IIS, but in powershell we can easily completed within single line of code (shown below).

New-SelfSignedCertificate -FriendlyName USProd_Certif -DnsName PRODCD-USCertificate -CertStoreLocation Cert:\LocalMachine\My

Note:  If you want to add more that one self-signed certificate, then all will be issued with same DNS name (which create in first).

 

 

What do you think?

I hope you have idea of how to Create custom name self signed certificate 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.

 

How to use appcmd.exe to renew a new certificate for Bulk HTTPS URLs (Bindings)

While using multiple IIS server in a Load Balanced Environment, it will be a lot of work and challenge of changing/updating the certificate for large numbers of URLs bindings. In that type of scenario we can achieve simply by single line of command by using the appcmd.

Syntax

appcmd renew Binding /oldCert:oldcerthash /newCert:newcerthash

Execution STEPS

  1. Open old Certificate which need to replace with New installed certificate 
  2. Open Details Tab >> Go to Thumbprint >>Copy entire value and paste in notepad (see below image). Ensure removing the space in the Thumbprint
  3. Open New Certificate make a note of New Thumbprint and copy
  4. Open command prompt in administrator mode and Go to C:\windows\system32\inetsrv.
  5. Run below command

Ex : appcmd renew Binding /oldCert:‎f2a0d6168c1813158a850a098819704c369bb5da                        /newCert:‎B17v0d6168c1813158a850a098819704c369bb3dr

      

Exporting and Importing bulk website bindings in IIS

While using multiple IIS servers in a Load Balanced Environment, it will be a lot of work to create all your website twice with the same settings on each webserver.  In this scenario, it will create more critical to create a large number of binding for each server, so there is possible to export and import your configuration from one webserver to the other by using the command.

Executed and Tested Version

OS : Windows 10
IIS : 10.0.15063.0

To Export the website/IIS Bindings:

Macking backup of IIS configuration is as simple as copying the directory into a backup directory, so you don’t need anything special to do it.  Just execute the below command in the Command prompt to make the backup copy in “C” drive with the file name Import_ProdBindings.xml

%windir%\system32\inetsrv\appcmd list site /config /xml > C:\Import_ProdBindings.xml

To Import the website/IIS Bindings:

As like Backup, it very simple to add the config to the IIS by using below command.

%windir%\system32\inetsrv\appcmd add site /in < C:\Import_ProdBindings.xml

OUTPUT:

Error :

I had faced the below error while exporting the config to the IIS. This error is due to the presence of “Default Web Site” in the targeted IIS.  So you can delete the existing one before executing the new config OR you can change the name of “Default Web Site” in the config and start the import from backup.

Pretty easy, eh?  Except for the dirty little secret everyone knows…remembering to do a backup before starting the Import! 

“ERROR ( message:Failed to add duplicate collection element “Default Web Site”. )”

Powershell : How to get Application and Systems Logs From Event Viewer

I would like to show how-to work with events under Applications and system Logs using Powershell. Whether it’s an error report, a warning, or just an informational log, one of the most common places for Windows to write logging information is to the event logs. Let we some of the reason to view the window’s log,

  • Checking for errors after an unexpected restart.
  • To check the reason for service stop.

The Get-Eventlog cmdlet is a powerful and flexible way of pulling data out of the event logs, both in interactive sessions and in scripts. The below code will execute and output the system and application error from the local computer

Example:

#Get log detail using Get-Eventlog cmdlet and here we filter by System Log.
#The -Newest 50 parameter, will get first 50 recent entries from a specific event log on the local computer.
$sysEvent = Get-Eventlog -Logname system -Newest 50 | where-object { $_.createddate -lt (get-date)}
# Filter only Error logs using EntryType parameter.
$sysError = $sysEvent | Where {$_.entryType -Match "Error"}
Write-Output "*******************************************************"
Write-Host "Event Log - System errors"
Write-Output "*******************************************************"
$sysError | Sort-Object EventID |
Format-Table EventID, Source, TimeWritten, Message -auto

#Filtering only by Application keyword for Application errors alone. 
$applicationEvent = Get-Eventlog -Logname application -Newest 50 | where-object { $_.createddate -lt (get-date)}
$applicationEvent = $applicationEvent | Where {$_.entryType -Match "Error"}
Write-Output "*******************************************************"
Write-Host "Event Log - Application errors"
Write-Output "*******************************************************"
$applicationEvent | Sort-Object EventID |
Format-Table EventID, Source, TimeWritten, Message -auto

OUTPUT:

Get-EventLog cmdlet :

Get-EventLog : Gets the events in an event log, or a list of the event logs, on the local or remote computers.

Syntax:

Get-EventLog [-LogName] <String> [-ComputerName <String[]>] [-Newest <Int32>] [-After <DateTime>]
             [-Before <DateTime>] [-UserName <String[]>] [[-InstanceId] <Int64[]>] [-Index <Int32[]>]
             [-EntryType <String[]>] [-Source <String[]>] [-Message <String>] [-AsBaseObject]
             [<CommonParameters>]

Execution on Remote Computers:

We don’t have credential parameter in the Get-EventLog. So Instead of the  Get-EventLog you may use the Get-WinEvent ,which support param the -Credential or use the  Get-WmiObject and class Win32_NTLogEvent

EX :

Get-EventLog -LogName "Windows PowerShell" -ComputerName "localhost", "TFS-Server1", "TFS-Server2"

 

 

Add Binding To IIS – PowerShell

Hi Guys, today we are going to disuses about how to add the binding to IIS using Powershell. In most case, during the deployments, the one of the painful activity is adding binding for new sites. So this below posts will help those members to one step towards of Automation.

The New-WebBinding cmdlet adds a new binding to an existing website.

#Assigining the URL which need to bind
$_WebsiteUrl = "www.dotnet-helpers.com"
#Name of the WEB SITE name created under Sites Folder(IIS)
$_TargetIISWebsite ="Default Web site"
#It has a method IsNullOrEmpty() which returns true if the passed string is null or empty.
if([string]::IsNullOrWhiteSpace($_TargetIISWebsite))
{     
  write-host "website not created." 
}   
else    
{       
  #TRIM: Removes all leading and trailing white-space characters from the current String object
  $WebsiteUrl = $_WebsiteUrl.Trim(' ')
}
foreach ($Website in $_WebsiteUrl)
{
  #We are adding the SSL binding to the Default Web Site using New-WebBinding cmdlets
  New-WebBinding -Name $web -IPAddress "*" -Port 80 -protocol http -HostHeader $Website -sslflags
  New-WebBinding -Name $web -IPAddress "*" -Port 443 -protocol https -HostHeader $Website -sslflags  
  write-host $Website "Binding created successfully on" $_TargetIISWebsite   
}
}

Explanation:

The New-WebBinding cmdlet adds a new binding to an existing website.

New-WebBinding -Name $web -IPAddress “*” -Port 80 -protocol http -HostHeader $Website -sslflags 0

-Name The name of the Web site on which the new binding is created.
-IPAddress The IP address of the new binding.
-Port The port used for the binding.
-Protocol The protocol to be used for the Web binding (usually HTTP, HTTPS, or FTP).
-HostHeader The host header of the new binding.
-SslFlags Indicates what type of certificate OR certificate storage the new website supports. Only the below values are valid:

0 (Regular certificate in Windows certificate storage),
1 (SNI certificate),
2 (central certificate store),
3 (SNI certificate in central certificate store).

 

 

What do you think?

I hope you have idea of how to add the binding to IIS 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.