Monday, 25 November 2013

Developing Powershell scripts with Notepad++

Not sure how many are using Notepad++ for developing Powershell, but I am using Notepad++ every time I develop. Being Powershell developer, it helps alot due to following reasons: 

1. Syntax highlighting : This is really easy and you can also edit the color code you want. You can download syntax highlighter or you can make your definition. These things are so easy. Just go to style configurator and set the color you want. 

2. Block Collapsing : The + sign to the left of function block or if statement makes code more and more manageable. ALT+1 and ALT+2 can be used for different levels collapse you want. 

3. Freeware : This tool is free and you don't have to convince your manager. Just request to download. You can also find portable version of Notepad++ also.

Please see the download location at - http://notepad-plus-plus.org/

Powershell Basics : Pyramid program

I remember those old days, when I was learning programming. Making pyramid, paliendrome, fibonacci series, factorial and so many. Basically, these all were little difficult in those days and now they look like building block for making a programmer. Aaah! what a philosophy. 

Recalling those days, I am writing the same pyramid program in powershell. 
I have written one-liner:

for ($x =0; $x -lt 21; $x++) { "*" * $x }



Yes, this is sufficient! 
If you are learning programming with Powershell, you make seek my help. I can give you roadmap. 

Find the disk volumes in host

WMI gives a lot of such important information which makes windows administration more manageable. Scripting becomes more and more robust than ever before. 

Powershell can be used to call WMI objects and we can get so much information out of it. 

CODE : 
get-wmiobject win32_logicaldisk | select DeviceId,Size, FreeSpace



You might get a result in proper tabular format. There are lot many scripts possible with this. 
1. Script to report low disk space
2. Script to display disk inventory in multiple hosts 

If you have trouble writing scripts mentioned above, just add your request in comment,  I will pick from there.

Wednesday, 20 November 2013

Jump Start to Powershell

Powershell is one of command shell alternative for handling command line based operations and scripting.

Powershell is based on .NET Framework. It has nearly all the features available in other .NET Framework related programming languages.
Powershell was initially named as Monad, but it was later named as Powershell.
The programming style of Powershell is similar to Perl and Korn shell and similar to C# or VB.NET. 
Powershell can be used in Windows Core installation for administrative purposes. 

How to install Powershell?

Installation of Powershell is not required for Windows 2008 and Windows 7.. 

To check if Powershell is installed-
1. Goto Start > Run.
2. Type cmd to open command prompt.
3. Type below command -
where powershell 

If Powershell is not installed, you will get below output-
INFO: Could not find files for the given pattern(s).

You may install the version 1 or version 2 of Powershell based on the machine type and operating system. Please google and find the link, I am skipping providing link as it might change in future. 


Powershell command line

Powershell command line is nearly the same as Command prompt. However, it looks bit different in background color which is blue by default.





 Hello world!

This is simple to just write Hello world! Just type in below command -
echo Hello world!

But, I will write a script for the same which will have an argument. 

Writing your first script in Powershell:

1. Powershell script must be a script with *.ps1 extension. 
2. Your execution policy must be set correctly. I will discuss about execution-policy later, but for now, set to unrestricted to run your first script using below command.


set-executionpolicy Unrestricted;

3. Write the script as mentioned below -

function HelloWorld([string] $useInput)
{
     echo $userInput;
}

HelloWorld $args[0];

4. Save the script. I assume your named helloworld.ps1. 
5. Run the script

From Powershell command-line:

.\helloworld.ps1


Use .\ when the script is located on the same directory (present working directory)

You may also write the complete path. 

From Command prompt:
Powershell D:\helloworld.ps1

Points to remember :

1. The file extension must be .ps1
2. Powershell execution policy must be set appropriately to run the script on a given machine.
3. You cannot double click the powershell script similar to batch programs. 
4. A Powershell script run under .NET Framework. It can include all the libraries which C# or VB.NET can utilize. 

Tuesday, 19 November 2013

Creating modules with Powershell

Powershell modules are extension to inbuilt cmdlets. You may download third-party modules or you can write them using C#. Along with some installation, modules are installed in Powershell.

List the modules available: 

Use get-module to list the modules.

Import an existing module: 

import-module <module_name>

Writing your own module with Powershell

You can write your own module in Powershell using below steps:
1. Create a file with below content: 

function do-nothing()
{
echo "You are in nothing"
}

function do-something( $i, $j)
{
echo "Result : $($i + $j)"
}

2. Save the file with .psm1 extension. I use test.psm1 as filename.

3. Import the module 

import-module c:\tst\test.psm1

4. Check if module is loaded

PS D:\Org\Powershell> Get-Module

ModuleType Name ExportedCommands
---------- ---- ----------------
Script test {do-something, do-nothing}


5. Run the command used 

PS D:\Org\Powershell> do-something 5 6
Result : 11


CONCLUSION

Overall, we have below advantages using this approach:
1. Increases code manageability
Any changes made in one module is copied over all the modules.

2. Increases code reusability :
You can use common tasks like sending mails or logging in one module and share in all the scripts.

3. Team work
If a team of people working, working in modules reduces burden on single person and everyone owns his own part.

Monday, 18 November 2013

Thanks!!

Thanks for making this blog successful!! 
I get so many mails from this blog and this shows the great success of this blog!!

Get Cluster details with Powershell

Windows Cluster can be found in every enterprise. We want to have high availability of our server application which increases the scope of having clusters. We are talking about Windows clusters only, your requirement might not match if you are using third-party clusters by Veritas and others.

My requirement of getting cluster related information was different but it might suit any Windows administrator. Basically, I am DBA Engineer and I was writing script which could collect SQL Server cluster information. So it required to know if there are below resources available:

1. Network resource
2. Disk Resource
3. Nodes

PREREQUISITES

We are going to use cmdlets which are not available in Powershell as native. Yeah, you understood - we are going to import module. But I am not talking about any third party material (which I don't like). The module is provided by Microsoft itself. If you have Windows 2008 and above, you might find the module already. For Windows 2003 and previous versions, I will let you know different set of commands (I don't leave any stone unturned).

INITIAL STEPS

Step [1] Find if module is available
Please run below command to list all the modules.

get-module -listAvailable

Step [2] Import the Module

import-module failoverclusters

If you are writing any script, make sure you import the module.

ACTION 

1. Find the Network resource

Here, I will just tell you the cmdlet to know what all network resource names can be seen on Windows cluster.

Get-ClusterNetwork -Cluster <cluster name>

2. Find the Disk resource 

Get-ClusterResource -Cluster <Cluster name>

3. Cluster nodes info

Get-ClusterNode -Cluster <Cluster Name>

4. Find Cluster groups available

Get-ClusterGroup -Cluster <Cluster Name>

Below is the list of cmdlets which can help you manage cluster:

Add-ClusterDisk
Make a new disk available for use in a failover cluster. The disk (LUN) must be exposed to all nodes in the failover cluster, and should not be exposed to any other servers.

Add-ClusterFileServerRole
Create a clustered file server (resource group that includes one or more disks, on which you can create shared folders for users).

Add-ClusterGenericApplicationRole
Configure high availability for an application that was not originally designed to run in a failover cluster.

Add-ClusterGenericScriptRole
Configure an application controlled by a script that runs in Windows Script Host, within a failover cluster.

Add-ClusterGenericServiceRole
Configure high availability for a service that was not originally designed to run in a failover cluster.

Add-ClusterGroup
Add an empty resource group to the failover cluster configuration, in preparation for adding clustered resources to the group.

Add-ClusterNode
Add a node (server) to a failover cluster. Before adding the new node, you should run validation tests on the existing nodes together with the proposed new node.

Add-ClusterPrintServerRole
Create a clustered print server (a resource group that includes a printer and a disk for storing print job information and printer drivers).

Add-ClusterResource
Add a resource to a clustered service or application (resource group) in a failover cluster.

Add-ClusterResourceDependency
Add a resource to the list of resources that a particular resource depends on (using AND as the connector) within a failover cluster. Existing dependencies will remain in the list.

Add-ClusterResourceType
Add a resource type to a failover cluster, and specify information such as the dynamic-link library (DLL) to use with that resource type.

Add-ClusterServerRole
Add a group containing only a client access point and storage to the failover cluster configuration.

Add-ClusterSharedVolume
Make a volume available in Cluster Shared Volumes in a failover cluster.

Add-ClusterVirtualMachineRole
Create a clustered virtual machine, that is, a virtual machine that can be failed over if necessary to a different server in the failover cluster.

Block-ClusterAccess
Prevent the specified user or users from accessing a failover cluster.

Clear-ClusterDiskReservation
Clear the persistent reservation on a disk in a failover cluster.

Clear-ClusterNode
Clear the cluster configuration from a node that was evicted from a failover cluster.

Get-Cluster
Get information about one or more failover clusters in a given domain.

Get-ClusterAccess
Get information about permissions that control access to a failover cluster.

Get-ClusterAvailableDisk
Get information about the disks that can support failover clustering and are visible to all nodes, but are not yet part of the set of clustered disks.

Get-ClusterGroup
Get information about one or more clustered services or applications (resource groups) in a failover cluster.

Get-ClusterLog
Create a log file for all nodes (or a specific node) in a failover cluster.

Get-ClusterNetwork
Get information about one or more networks in a failover cluster.

Get-ClusterNetworkInterface
Get information about one or more network adapters in a failover cluster.

Get-ClusterNode
Get information about one or more nodes (servers) in a failover cluster.

Get-ClusterOwnerNode
For a resource in a failover cluster, get information about which nodes can own the resource. For a clustered service or application (a resource group), get information about the order of preference among owner nodes.

Get-ClusterParameter
Get detailed information about an object in a failover cluster, such as a cluster resource. This cmdlet is used to manage private properties for a cluster object.

Get-ClusterQuorum
Get information about the quorum configuration of a failover cluster.

Get-ClusterResource
Get information about one or more resources in a failover cluster.

Get-ClusterResourceDependency
Get information about the dependencies that have been configured between clustered resources in a failover cluster.

Get-ClusterResourceDependencyReport
Generate a report that lists the dependencies between resources in a failover cluster.

Get-ClusterResourceType
Get information about one or more resource types in a failover cluster.

Get-ClusterSharedVolume
Get information about Cluster Shared Volumes in a failover cluster.

Grant-ClusterAccess
Grant access to a failover cluster, either full access or read-only access.

Move-ClusterGroup
Move a clustered service or application (a resource group) from one node to another in a failover cluster.

Move-ClusterResource
Move a clustered resource from one clustered service or application to another within a failover cluster.

Move-ClusterSharedVolume
Move a Cluster Shared Volume to ownership by a different node in a failover cluster.

Move-ClusterVirtualMachineRole
Move the ownership of a clustered virtual machine to a different node.

New-Cluster
Create a new failover cluster. Before you can create a cluster, you must connect the hardware (servers, networks, and storage), and run the validation tests.

Remove-Cluster
Destroy an existing failover cluster. The affected servers will no longer function together as a cluster.

Remove-ClusterAccess
Remove a user from the access list on the cluster.

Remove-ClusterGroup
Remove a clustered service or application (also called a resource group) from a failover cluster.

Remove-ClusterNode
Remove a node from a failover cluster. After the node is removed, it no longer functions as part of the cluster unless you add it back to the cluster.

Remove-ClusterResource
Remove a clustered resource from the failover cluster.

Remove-ClusterResourceDependency
Remove a dependency between two resources in a clustered service or application within a failover cluster.

Remove-ClusterResourceType
Remove a resource type from a failover cluster.

Remove-ClusterSharedVolume
Remove a volume from the Cluster Shared Volumes in a failover cluster, and place it in Available Storage in the cluster.

Repair-ClusterSharedVolume
Run repair tools on a Cluster Shared Volume locally on a cluster node.

Resume-ClusterNode
Resume activity on a failover cluster node after you have suspended it (that is, paused it).

Resume-ClusterResource
Turn off maintenance for a disk resource or Cluster Shared Volume within a failover cluster.

Set-ClusterLog
Set the size and level of detail for the cluster log.

Set-ClusterOwnerNode
For a resource in a failover cluster, specify which nodes can own the resource. For a clustered service or application (a resource group), specify information about the order of preference among owner nodes.

Set-ClusterParameter
Control specific properties of an object in a failover cluster, such as a resource, a group, or a network.

Set-ClusterQuorum
Configure quorum options for a failover cluster.

Set-ClusterResourceDependency
Specify the resources that a particular resource depends on within a failover cluster. Existing dependencies will be overwritten by the dependencies that you specify.

Start-Cluster
Start the Cluster service on all nodes of the cluster on which it is not yet started.

Start-ClusterGroup
Bring one or more clustered services and applications (also known as resource groups) online on a failover cluster.

Start-ClusterNode
Start the Cluster service on a node in a failover cluster.

Start-ClusterResource
Bring a resource online in a failover cluster.

Stop-Cluster
Stop the Cluster service on all nodes in a failover cluster, which will stop all services and applications configured in the cluster.

Stop-ClusterGroup
Take one or more clustered services and applications (also known as resource groups) offline on a failover cluster.

Stop-ClusterNode
Stop the Cluster service on a node in a failover cluster.

Stop-ClusterResource
Take a resource offline in a failover cluster.

Suspend-ClusterNode
Suspend activity on a failover cluster node, that is, pause the node.

Suspend-ClusterResource
Turn on maintenance for a disk resource or Cluster Shared Volume so that you can run a disk maintenance tool without triggering failover.

Test-Cluster
Run validation tests for failover cluster hardware and settings. Tests can be run both before and after a cluster is set up.

Test-ClusterResourceFailure
Simulate a failure of a cluster resource.

Update-ClusterIPResource
Renew or release the DHCP lease for an IP address resource in a failover cluster.

Update-ClusterVirtualMachineConfiguration
Refresh the configuration of a clustered virtual machine within a failover cluster

Equivalent commands for pervious version of Windwos 2003: 

Cluster.exe <Cluster Name> /prop
Get-Cluster <Cluster Name> | fl *

Cluster.exe <Cluster Name> /priv
Get-Cluster <Cluster Name> | Get-ClusterParameter

Cluster.exe <Cluster Name> group
Get-ClusterGroup -Cluster <Cluster Name>

Cluster.exe <cluster Name> node
Get-ClusterNode -Cluster <Cluster Name>

Cluster.exe <cluster name> res
Get-ClusterResource -Cluster <Cluster name>

Cluster.exe <Cluster name> net
Get-ClusterNetwork -Cluster <cluster name>

Cluster.exe <cluster name> netint
Get-ClusterNetworkInterface -Cluster <cluster name>

Cluster.exe <cluster name> group /move:<Node name>
Move-ClusterGroup -Name <group name> -Node <Node name> -Cluster <cluster name>

Cluster.exe log
Get-ClusterLog

Cluster.exe <cluster name> /create …
New-Cluster

Cluster.exe <cluster name> group /add
Add-ClusterGroup

Cluster.exe <cluster name> group <group name> /on
Start-ClusterGroup -Name <group name> -Cluster <cluster name>

CONCLUSION
As you can see the module failoverclusters gives you more and more options to manage cluster. Sorry, I could not add any script for this article, but you may ask me in case you want, I will reply once I get time.

Sunday, 20 October 2013

Display top n lines or last n lines of a file

Often we reach to a situation where we need to get top 10 or 100 lines of a file.
These commands are fairly simple in Unix shell programming and most of you must have used Head and Tail commands. Those commands work really fast and accurate.

Keeping these points in mind, I dig something and want to share will all of you.

How to use Head and Tail Commands in Powershell?

To get the top 10 lines -
Get-Content ".\file_test.txt" | select -First 10

To get the top 10 lines -

Get-Content ".\file_test.txt" | select -Last 10

Easy! This is power of Powershell !

Some more Examples:

Problem: Write a command to get 3rd line of a file.

Solution:
Get-Content ".\file_test.txt" | select -First 3 | select -Last 1

Problem: Write a command to skip 10 lines from top and display rest all lines of file.

Solution:
Get-Content ".\file_test.txt" | select -Skip 10

But this approach has one drawback, when file is so big, it takes a little more time to produce results. I am digging more and more to get this done with another approach, keep checking this article..

Enjoy Scripting!!