Tuesday, 25 August 2015

Parameters in PowerShell

Just Think about how cmdlets know What to do with  Given information.Here comes the Parameters, Which tells cmdlets what to do with given data. Again We need help ... Get-Help.

Do a Get-Help on a cmdlet,Say Get-ChildItem.

PS C:\> Get-Help Get-ChildItem 

    Gets the items and child items in one or more specified locations.
    Get-ChildItem [[-Path] <String[]>] [[-Filter] <String>] [-Exclude <String[]>] [-Force] [-Include <String[]>] [-Name] [-Recurse] [-UseTransaction [<SwitchParameter>]] 
    Get-ChildItem [[-Filter] <String>] [-Exclude <String[]>] [-Force] [-Include <String[]>] [-Name] [-Recurse] -LiteralPath <String[]> [-UseTransaction 
    [<SwitchParameter>]] [<CommonParameters>]

Here you will get the Help For Get-ChildItem cmdlet and While checking the syntax for this cmdlet, you can see  some Paramaters, which begns with a '-' character

[-Path] <String[]>
The Path Parameter specifies the path to one or more locations,that's why you can see 'String[]' , which represents multiple string inputs.used

[-Filter] <String>
Specifies a Filter for the path parameter,Wildcards can be 

-Include <String[]
As the name,include parameter includes only paths for the strings specified. This parameter accepts Wildcards.

-Exclude <String[]
As the name,exclude parameter omits paths for the strings specified. This parameter accepts Wildcards.If Specified,

-Name <SwitchParameter>
Only names of the items in the locations will be retrieved.

-Recurse <SwitchParameter>
If specified , this will retrieves items in specified Locations and in all child items of the Locations.

-Force <SwitchParameter>
Overrides the restrictions that prevents the cmdlet from executing if Specified.

-LiteralPath <String[]>
Specifies a path to one or more ations, but here it is exactly used as it is typed,In Path parameter, We can use wildcards , which are not allowed here.This cmdlet supports the common parameters:
-Verbose, -Debug, -ErrorAction, -ErrorVariable  and -Outvariable.

Types Of Parameters

  • Named Paramters
  • Positional Parameters
  • Switch Paramters
  • Common Parameters
Named Paramters:- Name parameters Works like  key value pairs. You specify the name of the paarameter which starts with a Hyphen and a space between the value of that parameter.

Positional Parameters:- Positional parameters are parameters that needs to be specified in certain position.For named parameters, position is not having any importance as they are named and can be specified any where, Whereas Positional parameters has to be provided in its own position.

here in Get-Childitem cmdlet, Parameter -Path is having position 1.So it is not mandatory to name the parameter. Similarly Parameter -Filter has the position 2.

Switch Paramters:- If named parameters are like key value pairs, switch parameters are just opposite.Switch parameters represents its presence,like a Physical Switch to Turn Light "On or Off".

Get-ChildItem -Path C:\Windows -Recurse

Here We use -Recurse Switch Parameter to get items fom the subdirectories of "C:\Windows"

Common Parameters:- There are some Commomn Parameters which is common for almost all cmdlets in PowerShell.
  • -Verbose <Switch>
  • -Debug <Switch>
  • -ErrorAction <Value>
  • -ErrorVariable <Value>
  • -OutVariable <Value>

Monday, 24 August 2015

The Verb-Noun Nomenclature

Windows PowerShell Uses a Verb-Noun pair for the names of cmdlets and for their derived Microsoft .Net FrameWork Classes. For example, The Get-Command cmdlet provided by Windows PowerShell is used to retrieve all the cmdlets that are registered in Windows PowerShell.The Verb part of the name identifies the action that the cmdlets performs.The noun part of the name identifies the entity on which the action is preferred.

PowerShell cmdlets always consist of a Verb,Which represents an action and a noun which acts on it.
This naming conventions helps us to find the right cmdlets so easy.
Think about What action you need to do on the console ,Say 'Get'. then what you need ,Say 'Command'.
After all, its Get-Command,

PS C:\> Get-Command

CommandType     Name                                               Version    Source                                                                                        
-----------     ----                                               -------    ------                                                                                        
Alias           Add-ProvisionedAppxPackage                         3.0        Dism                                                                                          
Alias           Add-VMToCluster                              FailoverClusters                                                                              
Alias           Add-WindowsFeature                           ServerManager                                                                                 
Alias           Apply-WindowsUnattend                              3.0        Dism                                                                                          
Alias           Begin-WebCommitDelay                         WebAdministration                                                                             
Alias           End-WebCommitDelay                           WebAdministration                                                                             
Alias           Expand-IscsiVirtualDisk                      IscsiTarget                                                                                   
Alias           Export-DnsServerTrustAnchor                  DnsServer                                                                                     
Alias           Flush-Volume                                 Storage                                                                                       
Alias           Get-GPPermissions                            GroupPolicy                                                                                   
Alias           Get-ProvisionedAppxPackage                         3.0        Dism                                                                                          
Alias           Get-VpnServerIPsecConfiguration              RemoteAccess                                                                                  
Alias           Initialize-Volume                            Storage                                                                                       
Alias           Move-SmbClient                               SmbWitness                                                                                    
Alias           Reconcile-DhcpServerv4IPRecord               DhcpServer                                                                                    
Alias           Remove-ProvisionedAppxPackage                      3.0        Dism                                                                                          
Alias           Remove-VMFromCluster                         FailoverClusters                                                                              
Alias           Remove-WindowsFeature                        ServerManager                                                                                 
Alias           Set-GPPermissions                            GroupPolicy                                                                                   
Alias           Set-VpnServerIPsecConfiguration              RemoteAccess                                                                                  
Alias           Write-FileSystemCache                        Storage                                                                                       
Function        A:                                                                                                                                                          
Function        Add-BCDataCacheExtension                     BranchCache                                                                                   
Function        Add-BgpCustomRoute                           RemoteAccess                                                                                  
Function        Add-BgpPeer                                  RemoteAccess                                                                                  
Function        Add-BgpRouter                                RemoteAccess                                                                                  
Function        Add-BgpRoutingPolicy                         RemoteAccess                                                                                  
Function        Add-BgpRoutingPolicyForPeer                  RemoteAccess                                                                                  
Function        Add-BitLockerKeyProtector                    BitLocker                                                                                     
Function        Add-DAAppServer                              RemoteAccess                                                                                  
Function        Add-DAClient                                 RemoteAccess                                                                                  

Here , You performed a Get on Command which gives you all the cmdlets available in you Computer.

To Get Approved Verbs in PowerShell, We have a cmdlet.


This cmdlet Gives you all the approved verbs in PowerShell.

PS C:\> Get-Verb

Verb        Group         
----        -----         
Add         Common        
Clear       Common        
Close       Common        
Copy        Common        
Enter       Common        
Exit        Common        
Find        Common        
Format      Common        
Get         Common        
Hide        Common        
Join        Common        
Lock        Common        
Move        Common        
New         Common        
Open        Common        
Optimize    Common        
Pop         Common        
Push        Common        
Redo        Common        
Remove      Common        
Rename      Common        
Reset       Common        
Resize      Common        
Search      Common        
Select      Common        
Set         Common        
Show        Common        
Skip        Common        
Split       Common        
Step        Common        
Switch      Common        
Undo        Common        
Unlock      Common        
Watch       Common        
Backup      Data          
Checkpoint  Data          
Compare     Data          
Compress    Data          
Convert     Data          
ConvertFrom Data          
ConvertTo   Data          
Dismount    Data          
Edit        Data          
Expand      Data          
Export      Data          
Group       Data          
Import      Data          
Initialize  Data          
Limit       Data          
Merge       Data          
Mount       Data          
Out         Data          
Publish     Data          
Restore     Data          
Save        Data          
Sync        Data          
Unpublish   Data          
Update      Data          
Approve     Lifecycle     
Assert      Lifecycle     
Complete    Lifecycle     
Confirm     Lifecycle     
Deny        Lifecycle     
Disable     Lifecycle     
Enable      Lifecycle     
Install     Lifecycle     
Invoke      Lifecycle     
Register    Lifecycle     
Request     Lifecycle     
Restart     Lifecycle     
Resume      Lifecycle     
Start       Lifecycle     
Stop        Lifecycle     
Submit      Lifecycle     
Suspend     Lifecycle     
Uninstall   Lifecycle     
Unregister  Lifecycle     
Wait        Lifecycle     
Debug       Diagnostic    
Measure     Diagnostic    

To Get the total number of Verbs, use

PS C:\> (Get-Verb).count

Thursday, 20 August 2015

Using Get-Help ?

Get-Help is one of the most important and frequently used cmdlet in PowerShell in My opinion and this has been First Said by the Inventor himself, Mr. Jeffrey Snover .

Why because , a person who doesn't know about a command and its use, Get-Help is the best way to figure it out.

So lets start with Get-Help .

Open Windows Powershell and Type Get-Help.

Here You will get help about Get-Help itself.

How to Get-help for a cmdlet ?

PS C:\> Get-Help -Name Get-ChildItem and hit enter.

Here it Tells about the Get-Childitem cmdlet that it Gets the files and Folders in a file system drive.

and you can see the syntax here.

    Get-ChildItem [[-Path] <String[]>] [[-Filter] <String>] [-Exclude <String[]>] [-Force] [-Include <String[]>] [-Name] [-Recurse] [-UseTransaction
    [<SwitchParameter>]] [<CommonParameters>]

    Get-ChildItem [[-Filter] <String>] [-Exclude <String[]>] [-Force] [-Include <String[]>] [-Name] [-Recurse] -LiteralPath <String[]> [-UseTransaction
    [<SwitchParameter>]] [<CommonParameters>]

    Get-ChildItem [-Attributes <FileAttributes]>] [-Directory] [-File] [-Force] [-Hidden] [-ReadOnly] [-System] [-UseTransaction] [<CommonParameters>]

and the detailed information is provided by the Description Which includes the link for the help.

    The Get-ChildItem cmdlet gets the items in one or more specified locations. If the item is a container, it gets the items inside the container, known as child
    items. You can use the Recurse parameter to get items in all child containers.

    A location can be a file system location, such as a directory, or a location exposed by a different Windows PowerShell provider, such as a registry hive or a
    certificate store.
    In a file system drive, the Get-ChildItem cmdlet gets the directories, subdirectories, and files. In a file system directory, it gets subdirectories and files.

    By default, Get-ChildItem gets non-hidden items, but you can use the Directory, File, Hidden, ReadOnly, and System parameters to get only items with these
    attributes. To create a complex attribute search, use the Attributes parameter. If you use these parameters, Get-ChildItem gets only the items that meet all
    search conditions, as though the parameters were connected by an AND operator.

    Note: This custom cmdlet help file explains how the Get-ChildItem cmdlet works in a file system drive. For information about the Get-ChildItem cmdlet in all
    drives, type "Get-Help Get-ChildItem -Path $null" or see Get-ChildItem at http://go.microsoft.com/fwlink/?LinkID=113308.

And more, You will get related cmdlets too !!! 

If you need examples, Just type 
PS C:\> Get-Help Get-ChildItem -Examples

Here you will get examples for the Get-Childitem cmdlet, if not you can update the help files uisng
Update-Help cmdlet.

So, The best way to learn PowerShell is , Open Windows PowerShell and type Get-Help,
Then Get-Help Get-Help -Examples .

You Just want to explore it That's all...

Wednesday, 19 August 2015

Using The Absolute Path

Today i'm Going to Write something about using Absolute Path.

Lets Start with a try, open windows PowerShell and type dir 

PS C:\users\kvprasoon> dir

    Directory: C:\users\kvprasoon

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        8/19/2015   2:06 PM                Contacts
d-----        8/19/2015   2:06 PM                Desktop
d-----        8/19/2015   2:06 PM                Documents
d-----        8/19/2015   2:06 PM                Downloads
d-----        8/19/2015   2:06 PM                Favorites
d-----        8/19/2015   2:06 PM                Links
d-----        8/19/2015   2:06 PM                mcafee dlp quarantined files
d-----        8/19/2015   2:06 PM                Music
d-----        8/19/2015   2:06 PM                Pictures
d-----        8/19/2015   2:06 PM                Saved Games
d-----        8/19/2015   2:06 PM                Searches
d-----        8/19/2015   2:06 PM                Videos
-a----        3/12/2015  12:43 PM              0 msinfo.txt

dir will list contents in The current directory.

Here you can see a text file name msinfo.txt, Lets try to open it.
Normally , we use to do PS C:\users\kvprasoon> msinfo.txt

Here its Throws an error Saying
msinfo.txt : The term 'msinfo.txt' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a
path was included, verify that the path is correct and try again.
At line:1 char:1
+ msinfo.txt
+ ~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (msinfo.txt:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

Yes, There is no cmdlet,Function,Script or any other operable program named msinfo.txt.
PowerShell need Absolute path to open a file and is a wonderful feature in PowerShell when we think about security.
So what is Absolute Path ?
 Absolute path is a path for a file using its complete full path name.

and you can see, Powershell is well enough to understand what we were trying to do and is show by providing suggestion. And here also we've got one.You can see it next line of the thrown error.

Suggestion [3,General]: The command msinfo.txt was not found, but does exist in the current location. Windows PowerShell does not load commands from the current loca
tion by default. If you trust this command, instead type: ".\msinfo.txt". See "get-help about_Command_Precedence" for more details.

So PowerShell is suggesting us by saying that msinfo.txt is there in the location, But Windows PowerShell Does not loads commands from current location by default.The way to accomplish this is by using .'\'  or by typing the fullpath 'c:\Users\Kvprasoon\msinfo.txt' .

Here it is,

This is one of the way how Windows PowerShell gives us security in running executables and other scripts from the current location.

Monday, 17 August 2015

The Shell As a Calculator

Calculator !!!
Yes... We can use windows PowerShell as a Calculator.
Try it out, Just try an addition.
Open PowerShell, and type 4+6 and hit enter.

PS C:\Users\kvprasoon> 4+6

You Can use all arithmetic operations in PowerShell as you see in Above example.
Here is another example for this.
Here we have a little strange calculation, and its bit different.
Just type
PS C:\Users\kvprasoon> 1kb
Yes, It works here. Calculation in PowerShell will works with Units too.
Here it returns output in bytes.
And Finally, Interesting thing is PowerShell is well enough to understand hexadecimal values.

Sunday, 16 August 2015

List The Items in a directory

If we are in our cmd.exe, We use the command 'dir', which lists the contents inside a directory.

How PowerShell do this ?

Open windows PowerShell and type 'dir' .

PS C:\inetpub> dir

    Directory: C:\inetpub

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        10/3/2014   4:19 PM                custerr
d-----        1/12/2015   2:41 PM                ftproot
d-----        6/27/2015   5:44 PM                history
d-----        1/12/2015  12:48 PM                logs
d-----        1/12/2015   2:48 PM                temp
d-----        1/12/2015   2:48 PM                wwwroot

Woow... Its works here too :)

yes,It'll and the unix command 'ls' too works.
These are Aliases for the powershell cmdlet 'Get-Childitem' which is the original PowerShell way of listing items in a directory.

PS C:\inetpub> Get-ChildItem

    Directory: C:\inetpub

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----        10/3/2014   4:19 PM                custerr
d-----        1/12/2015   2:41 PM                ftproot
d-----        6/27/2015   5:44 PM                history
d-----        1/12/2015  12:48 PM                logs
d-----        1/12/2015   2:48 PM                temp
d-----        1/12/2015   2:48 PM                wwwroot

Then by using 'ls'

Saturday, 15 August 2015

Lets Customize The Console

When we say Customizing the console, What does it means ?

It means nothing but changing the default settings of the console.
Its about changing the appearance and other simple settings of the console.

Here is a way to accomplish this.

Click the PowerShell icon on the top left of the title bar of the window to open it.
This will give you a context menu and by selecting properties to open the dialog box to customize the settings

The options

Here you are seeing the options for PowerShell v 5.0.
Here you will be able to set
  • Cursor size:- Where you adjust the size of the blinking cursor.
  • Command History:- Where you have the option to set Buffer Size, Which is a setting how many commands should the console remembers and discard the duplicates option will remove if we use the command more than once and will keep only once.
  • Edit Options:- We can enable Quick edit mode to , Which makes us easy to select, copy and insert text. The insert mode makes sure that’s the new characters will be added without erasing text. And we have the option to enable/Disable ctrl key options and Filtering the contents in clipboard while copying.
Font Setting

In This Font Tab, You Can Choose Both Font settings,

Default Font Will be 'Raster'. Here you can change the font size,.If you need bold, You can check 'Bold fonts' option and you can view all these setting changers in preview window.

The Layout

This Layout Tab Determines the Windows Size, Window Position and Screen Buffer Size for The PowerShell console.
  • Screen Buffer Size:- Here You Can Specify the Width and Height for the console which determines how much information the console should 'remember' and how for back you can scroll the scroll bars.
  • Window size:p:- Here you can specify the Height and Width for the PowerShell console window.
  • Window position:-Here is the place where you can specify the Window Position that,  Where the console should open whenever you open Windows PowerShell console in You PC.You Can Check 'Let system Position windows' option to Let the system determine where the console should open.
NOTE:- Its better to Assign same width For Window size and window Position .

Setting The color

On this tab, You Can Specify the color settings For your console.
  • Screen Text:-The Color for console text
  • Screen background:-Color For Console Background.
  • Popup Text:-Color For Popup Window(eg:- command History 'F7')
  • popup background:-The Background color for Popup window.
You Can Specify the colors by giving values for Red,Green and blue, So that you can get customized colors other than in the list.
$host.ui.RawUI.Foregroundcolor=”Black” <Enter>
$host.UI.RawUI.Backgroundcolor=”white” <Enter>

Thursday, 13 August 2015

About The Console

Starting from windows 7 and 2008 R2, PowerShell is installed by default. If you need windows PowerShell in older systems, You have to download and install it. It is included in WMF(Windows Management framework).
After installing PowerShell, you can find it by just clicking start(Windows 7 or later) and by typing 'PowerShell' or you can find it in c:\windows\system32\WindowsPowershell\v1.0\powershell.exe.

The best way is to use the 'Run'(Windows Key + R) and by typing PowerShell and hit enter. If you want to use PowerShell with elevated privileges, You should right click the icon and should select. 'Run As Administrator' option.

After PowerShell starts, You will get a Blue console with a cursor blinking.

As all programming language, Which starts by experimenting using 'HelloWorld'.
Just type HelloWorld and hit enter.

You will get error as 'Helloworld : The term 'Helloworld' is not recognized as the name of a cmdlet ...', Because PowerShell doesn't know what HelloWorld is.

For most of the console like cmd.exe , terminal etc. will have a help command. Here in PowerShell also we have the same.
Type 'help' and hit enter.

But, Here in PowerShell , we have a common structure for cmdlets.
it is a combination of a Verb and a Noun with a '-' in between.


Get-Help is the command that shows the help for each cmdlets. Here you typed help in the console and got output for the actual Get-Help cmdlet. Why because , we have 'Alias' for some cmdlets in PowerShell, If not we have the option to create one using New-Alias cmdlet.
help/man are the aliases for Get-Help cmdlet.

As in cmd.exe we have the option too break a running cmdlet by using Ctrl + C combination or by using Ctrl + Break combination.

After all , You may find that some of the commands in cmd.exe will work in PowerShell as well, But its not "some" , But its "most". Most of the commands in cmd will work in PowerShell as well as they are standalone executables.
ping ,ipconfig, netsh, net, md, chdir, dir are some of them.

Wednesday, 12 August 2015

What are cmdlets ?

A cmdlet is a lightweight command that is used in the Windows PowerShell environment. The Windows PowerShell runtime invokes these cmdlets within the context of automation scripts that are provided at the command line. The Windows PowerShell runtime also invokes them programmatically through Windows PowerShell APIs.Cmdlets perform an action and typically return a Microsoft .NET Framework object to the next command in the pipeline. 

Difference Between cmdlets and commands

Cmdlets are instances of .NET Framework classes; they are not stand-alone executables those can be created from as few as a dozen lines of code. Cmdlets do not generally do their own parsing, error presentation, or output formatting. Parsing, error presentation, and output formatting are handled by the Windows PowerShell runtime.Cmdlets process input objects from the pipeline rather than from streams of text, and cmdlets typically deliver objects as output to the pipeline and are record-oriented because they process a single object at a time.

Monday, 10 August 2015

What is PowerShell ?

Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework. PowerShell provides full access to COM and WMI, enabling administrators to perform administrative tasks on both local and remote Windows systems as well as WS-Management and CIM enabling management of remote Linux systems and network devices. [ref]