Tag Archives: thiyagu

PowerShell Comments

Same like other programming language, the comments in Powershell will not executed. Comments can be added to explain the function of the code and it can  be placed anywhere and anything between them will be treated as a comment. The powershell also supports single line and multi line comments.

Single Line Comments

SYNTAX: #

The comment with the # will handling single line comments. In PowerShell single line comments start with a hash symbol and everything to the right of the # will be ignored.

$MyFirstVaiable = "Hello" #Example for single line comments.

Multi-line Comments

Begin the comment with the <# tag, and end the comment with the #> tag for handling multiline. Multi-line comments are typically used to add descriptive help at the start of a script.

SYNTAX: <# #>

$MyFirstVaiable = "Hello" <# Example for Multiple line comments. 
                  This variable use to display hello #>

 

Working with PowerShell’s Data Types

An important property of a PowerShell variable is its name, which is always preceded by the dollar sign “$” and can only contain letters, numbers, and the underscore. If you feel a strong urge to use other characters, you have to enclose the name in curly braces. You should not use the name of variables that have been pre-defined.

Windows PowerShell uses the Microsoft .NET Framework data types. The poweshell can supports strings ,integers ,floating point numbers, strings, and Boolean values.You don’t have to explicitly declare the data type of a variable, the PowerShell automatically chooses the data type for you when you initialize the variable—that is,when you first assign a value.

Example: 1 

$GetNumber = Read-Host "Please enter you score" 
$Total = $GetNumber + $GetNumber
Write-Host "The Total Score is $Total"

PowerShell wrongly assumed that the data type of the variable $GetNumber is String. Because the arithmetic operator + is overloaded (the implementation of the operator depends on the arguments), the second line in the program add a string instead of a number.

The second argument of the operator + always has to be a number, so PowerShell automatically converts the data type of $GetNumber into Int32. However, the first argument can also be a string. The result is that PowerShell determines the value of the expression “5”+5, which is 55 ( concatenate the string). 

Example: 2

[INT]$GetNumber = Read-Host "Please enter you score" 
$Total = $GetNumber + $GetNumber
Write-Host "The Total Score is $Total"

In the above code snippet, we explicitly declared the number as Int32 (integer) by enclosing the type name in square brackets before the variable name. So the above variable is called “strongly typed”. If you declare the variable’s data type implicitly in our script the the variable is called as weakly typed.

Data Types:

Data Type Name Description
[Array] Array
[Bool] Value is TRUE or FALSE
[DateTime] Date and time
[Guid] Globally unique 32-byte identifier
[HashTable] Hash table, collection of key-value pairs
[Int32], [Int] 32-bit integers
[PsObject] PowerShell object
[Regex] Regular  expression
[ScriptBlock] PowerShell script block
[Single], [Float] Floating point number
[String] String
[Switch] PowerShell switch parameter
[TimeSpan] Time interval
[XmlDocument] XML document

Note: 

  • Windows PowerShell uses the Microsoft .NET Framework data types.
  • We don’t have to rely on PowerShell’s ability to automatically convert data types if we tell the interpreter that we are expecting a number as input.
  • This ensures that our script works as intended.
  • The explicitly declaring variable types can prevent unwanted results in your scripts and makes them more reliable.

PowerShell’s Variables

Windows PowerShell is designed to be an interactive command-line shell and it’s also a programming language. A PowerShell script is really nothing more than a simple text file. The file contains a series of PowerShell commands, with each command appearing on a separate line.

If we need to run the PowerShell script using the notepad then its filename needs to save as .PS1 extension.

Powershell Variables

Is It Case Sensitive

The answer is “YES”, power shell comments are case sensitive. 

  • As like other programming language, we need to declare the variable as like below. The main difference is we need to add prefix with ‘$’ symbol in the variable.
  • All we have to do to declare those variables is add a dollar sign, then use whatever name for the variable we want and no spaces are allowed in the variable name.

Example : 1

$name = 'Jon'
$number = 12345
$myGrade= 'D+'
$location = 'Charlotte'
// if we declare as string then it will treat as single word
$listofnumbers = 6,7,8,9

Example : 2

//Assign text to varible
$myFirstVarible = "Dotnet-helpers Welcomes you"
//Print the variable
$myFirstVarible 
//Concatenate Variable
$mySecondVarible = $myFirstVarible + "for PowerShell learning Curve" 
$mySecondVarible

Example : 3 Handling Dynamic Variables.

The Get-Variable cmdlet gets the PowerShell variables in the current console. You can retrieve just the values of the variables by specifying the ValueOnly parameter.

$UserAnna= “This is specific MSG for Anna”
$inputUser=”Anna"
$msgAnna = $(("User"+ $inputUser))
#-ValueOnly : Indicates that this cmdlet gets only the value of the variable.
Get-Variable -Name "$msgAnna" -ValueOnly

OUTPUT: This is specific MSG for Anna

 

Getting Help Information

The PowerShell includes detailed Help topics that explain PowerShell concepts. There are also Help topics for each cmdlet and provider and Help topics for many functions and scripts.

Getting Help for Cmdlets

To get Help about Windows PowerShell cmdlets, use the Get-Help cmdlet. Here let we see some of the cmdlets help.

To get a list of all the cmdlet Help topics in your session use below,

get-help -category cmdlet

OUTPUT

If we want to display one page of each Help topic at a time, then we need to use the help function or its alias man. For example, to display Help for the Get-ChildItem cmdlet, type

Man Get-ChildItem/Help Get-Childitem

If we need to known about all content in the Help topic, below cmdlet will help us with help of FULL keyword

get-help get-childitem -full

Getting Help About Providers

To get Help for a provider, type “Get-Help” followed by the provider name. For example, to get Help for the Registry provider, then type like below

get-help registry

To get all the list of provide use below

get-help -category provider

Getting Help About Functions and Scripts

We also use the help topics for many scripts and functions in Windows PowerShell. To display the Help for a function, type “get-help” followed by the function name.

get-help disable-psremoting

Getting Help Online

If we want to find the help online through the powershell then its can be acheive by the below command.

get-help <command-name> -online

For example, to get the online version of the Help topic about the Get-ChildItem cmdlet, type:+

get-help get-childitem -online

 

Introduction to Window’s PowerShell

Windows PowerShell is one of the most important Windows Server management tools that Microsoft has released. Windows PowerShell is one of the most important Windows Server management tools that Microsoft has released. An entirely new scripting environment for Windows, it consists of a new command shell and a new scripting language.We can write PowerShell scripts using any text editor, but you must need the PowerShell command shell for running.

Why its called Window Server Management?

Although PowerShell has been important in the Microsoft ecosystem ever since its release, as Windows Server 10 comes closer to release,we find that many features and deployments are significantly easier and more full-featured when carried out with PowerShell.  

How to get License?

PowerShell is built into Windows, so there is no fee or additional licensing cost. 

More about PowerShell:

Windows PowerShell is a command-line shell and scripting language designed specially for system administration. Built on the .NET Framework, Windows PowerShell helps IT professionals to control and automate the administration of the Windows operating system and applications that run on Windows Server environment. In PowerShell, administrative tasks are generally performed by cmdlets, specialized .NET classes implementing a particular operation. Sets of cmdlets may be combined together in scripts; executables, which are standalone applications; or by instantiating regular .NET classes.

Power shell versions: 

PowerShell Version Release Date Default Windows Versions
2.0 October 2009 Windows 7 Windows Server 2008 R2
3.0 September 2012 Windows 8 Windows Server 2012
4.0 October 2013 Windows 8.1 Windows Server 2012 R2
5.0 April 2014 Windows 10

Implementing jQuery.ajax() using Jquery

What is JQuery Ajax?

AJAX is standing for Asynchronous JavaScript and XML. It helps us to fetch the information from the server without reloading the page (ie., without refresh)JQuery is a great tool which provides a rich set of AJAX methods to develop great web application. jQuery provides the $.ajax method and several methods to make it easier to work with XHRs across browsers.

$.ajax

We can use the jQuery $.ajax() method in a different ways, let we discuss one by one.

  • we can pass it a configuration object as its argument
  • we can pass it a URL and an optional configuration object

SYNTAX: 

  • $.ajax(url,[options])
  • $.ajax([options])

Option Parameter:

Here i have listed few parameters which is using frequently.

Options Description
accepts The content type sent in the request header that tells the server what kind of response it will accept in return.
async By default, all requests are sent asynchronously. Set it false to make it synchronous.
beforeSend A callback function to be executed before Ajax request is sent.
cache A boolean indicating browser cache. Default is true.
complete A callback function to be executed when request finishes.
contentType A string containing a type of content when sending MIME content to the server.
data A data to be sent to the server. It can be JSON object, string or array.
dataType Type of data that we receiving back from the server.
error A callback function to be executed when the request fails.
headers An object of additional header key/value pairs to send along with request.
isLocal Allow the current environment to be recognized as local.
statusCode A JSON object containing numeric HTTP codes and functions to be called when the response has the corresponding code.
success A callback function to be executed when Ajax request succeeds.
timeout A number value in milliseconds for the request timeout.
type A type of http request for operation e.g. POST, PUT and GET. Default is GET.
url A string containing the URL to which the request is sent.

 

1) we can pass it a configuration object as its argument:

The $.ajax() method offers the ability to specify both success and failure callbacks. It have a felxibility
to take a configuration object, which can be defined separately. This approach make the developer to write reusable code.

var updateSuccessfully = function( obj ) {
$( '#divSuccess').html( "Updated successfully" );
};

var showError = function( req, status, err ) {
console.log( 'Went wrong while performing operation', status, err );
};

var ajaxUpdateRequest = {
url: '/dotnethelpers/UpdateUsers',
dataType: 'json',
success: updateSuccessfully,
error: showError
};

// Initiate the request
$.ajax(ajaxUpdateRequest);

Code Explanation:

updateSuccessfully,showError -: Both are methods created for handling success & error.
ajaxUpdateRequest :  It is declared as a separate method for handling the ajax operation. Inside the code, if it return success then ajax success will call the updateSuccessfully method and showError method when ajax operation fails. This approach make the developer to write reusable code.

2) we can pass it a URL and an optional configuration object

In this type, we can also call the $.ajax() method by passing it a URL and an optional configuration object.
This is very useful if we want to use the default configuration for $.ajax(), or if you want to use the same configuration for several URLs

$.ajax( '/dotnethelpers/UpdateUsers', {
type: 'GET',
dataType: 'json',
success: function( resp ) {
console.log( "Operation Performed Successfully" );
},
error: function( req, status, err ) {
console.log( 'Went wrong while performing operation',, status, err );
}
});

Code Explanation:

In above code, we can take advantage of passing url, type, datatype etc as an parameter. so it can be used by several other method for performing operation with different arguments.

 

Dynamically Adding meta tags in asp.net mvc

In this blog post, I am going to explain how we can create a meta tag dynamically using Asp .Net MVC. We are aware that Meta tag plays very important roles in Search engine optimization. It is necessary to add meta tag for best ranking on search engines. Let we discuss with simple example.

Controller :

From the below code, BindMetaTag method which will return a string with meta tags. This method will create a meta tag string and it will return to the calling method. Here I am using view bag to store the dynamically created meta tag string for binding in the view.

public ActionResult Index()
{
ViewBag.LoadMetaTag = BindMetaTag();
return View();
}

public string BindMetaTag()
{
System.Text.StringBuilder strDynamicMetaTag = new System.Text.StringBuilder();
strDynamicMetaTag.AppendFormat(@"<meta content='{0}' name='Keywords'/>", "Dotnet-helpers");
strDynamicMetaTag.AppendFormat(@"<meta content='{0}' name='Descption'/>", "creating meta tags dynamically in"+ " asp.net mvc by dotnet-helpers.com");
return strDynamicMetaTag.ToString();
}

View :

Here in the below code, @Html.Raw method is used to embed meta tag in _layout.cshtml page. This HTML.Raw method will embed output to head tag section without encoding html.

@Html.Raw(ViewBag.LoadMetaTag)

<h2>Dynamically creating meta tags in asp.net mvc</h2>

OutPut :

Now once you run your application and click on view source you will find meta tag for home page as show below.

 

Keep Cool Coding….