Category Archives: PowerShell

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.

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.

 

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.

Import-Module : The specified module ‘ServerManager’ was not loaded because no valid module file was found in any module directory

Error: Import-Module : The specified module ‘ServerManager’ was not loaded because no valid module file was found in any module directory.

While importing a module you may receive an error message :

Import-Module : The specified module 'ServerManager' was not loaded because no valid module file was found in any module directory.
At line:1 char:1
+ Import-Module ServerManager
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (ServerManager:String) [Import-Module], FileNotFoundException
+ FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand

Reason and Resoultion

This error happens when you are using a 64 bit version of powershell/powershell ISE, and trying to import a 32 bit module or you are using a 32 bit version of powershell/Powershell ISE, and trying to import a 64 bit module.

Note: This type of error is possible on multiple modules, not only servermanager .

 

What do you think?

I hope you have idea of how to resolve “The specified module ‘ServerManager’ was not loaded because no valid module file was found in any module directory. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.

Powershell Script for Website Availability Monitoring with Excel Report as output

In our previous post we already discussed about “How to check response code from a website using PowerShell by using single URL in example. Here let we discuss how to read the list of URLs from the text file and validate the list of URL . Finally script will generate the Excel file with the output result.

$URLListFile = "D:\PowerShell\URLList.txt"
#Reading the list of URLs from the URLList.txt file 
$URLList = Get-Content $URLListFile -ErrorAction SilentlyContinue
#Declaring Array
$Result = @()
$FormatGenerater = "<HTML><BODY background-color:grey><font color =""black""><H2> snfcms cert </H2>
</font><Table border=1 cellpadding=0 cellspacing=0><TR bgcolor=gray align=center><TD><B>URL</B>
</TD><TD><B>StatusCode</B></TD></TR>"
   
Foreach($URL in $URLList) 
{ 
  $time = try{ 
      $request = $null 
      #Measure-Command : Measures the time it takes to run script blocks and cmdlets.
      $response = Measure-Command { $request = Invoke-WebRequest -Uri $URL } 
      $response.TotalMilliseconds 
  }  
  catch 
  { 
   $request = $_.Exception.Response 
   $time = -1 
  }   
  $result += [PSCustomObject] @{ 
  Time = Get-Date; 
  Uri = $URL; 
  StatusCode = [int] $request.StatusCode; 
  } 
} 

if($result -ne $null) 
{  
    Foreach($Entry in $Result) 
    { 
        if($Entry.StatusCode -ne "200") 
        { 
            $FormatGenerater += "<TR bgcolor=grey>" 
        } 
        else 
        { 
            $FormatGenerater += "<TR bgcolor=lightgreen>" 
        } 
        $FormatGenerater += "<TD>$($Entry.uri)</TD><TD align=center>$($Entry.StatusCode)</TD></TR>" 
    } 
    $FormatGenerater += "</Table></BODY></HTML>" 
}  
$FormatGenerater | out-file D:\PowerShell\SiteValidation_Results.xls

OUTPUT Excel File:

 

What do you think?

I hope you have idea of how to check the Website Availability Monitoring with Excel Report as output. I would like to have feedback from my posts readers. Your valuable feedback, question, or comments about this article are always welcome.

How to get the array as input using Powershell

To read an array into Read-Host (get the array as input), you would need to put it in a loop because anything entered into Read-Host will be interpreted as a string. To make output in new line we can use $OFS, which is a special variable in PowerShell . OFS stands for Output field separator . You would use this to separate object/Array.

The .split() method is self explanatory, the .trim() method will simply remove leading and trailing spaces and leading and trailing line breaks

Example #1 : Getting Value as an Array by Looping

$arrayInput = @()
do {
$input = (Read-Host "Please enter the Array Value")
if ($input -ne '') {$arrayInput += $input}
}
#Loop will stop when user enter 'END' as input
until ($input -eq 'end')

$arrayInput

OUTPUT:

Example 2# : Alternative approach for handling the multiple inputs without loop.

#Set New line using OFS special Powershell variable
$OFS = "`n"
#Externally set input value as string
[string[]] $_ServerList= @()
#Get the input from the user
$_ServerList = READ-HOST "Enter List of Servers"
#splitting the list of input as array by Comma & Empty Space
$_ServerList = $_ServerList.Split(',').Split(' ')
$OFS + $_ServerList

Output:

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.