Thursday 26 November 2015

Why ' $_ ' Represents an Object ?


One of the key factor of PowerShell which made it most popular and successful Scripting language for management id the ability to process and handle everything as Objects and passing them throughout the pipeline .

Yes, The Pipeline. Lets check with an example.

PS C:\>Get-Service | Where-Object -FilterScript {$_.Status -eq 'Running'}

Status   Name               DisplayName
------   ----               -----------
Running  ALG                Application Layer Gateway Service
Running  AppHostSvc         Application Host Helper Service
Running  Appinfo            Application Information
Running  AudioEndpointBu... Windows Audio Endpoint Builder
Running  Audiosrv           Windows Audio
Running  BFE                Base Filtering Engine
Running  BITS               Background Intelligent Transfer Ser...
Running  BrokerInfrastru... Background Tasks Infrastructure Ser...
Running  Browser            Computer Browser
Running  CertPropSvc        Certificate Propagation
Running  ClipSVC            Client License Service (ClipSVC)
Running  CoreMessagingRe... CoreMessaging
Running  CryptSvc           Cryptographic Services
Running  CscService         Offline Files
Running  CxAudMsg           Conexant Audio Message Service
Running  DcomLaunch         DCOM Server Process Launcher
Running  DeviceAssociati... Device Association Service
Running  Dhcp               DHCP Client
Running  DiagTrack          Diagnostics Tracking Service
Running  Dnscache           DNS Client
Running  DPS                Diagnostic Policy Service
Running  DsmSvc             Device Setup Manager
Running  DsSvc              Data Sharing Service
Running  EFS                Encrypting File System (EFS)
Running  EventLog           Windows Event Log
Running  EventSystem        COM+ Event System


Here,we Have the services in My Computer which are currently running.

We used  Where-Object cmdlet to select only Running Services and -FilteScript Parameter to filter the output of Get-Service cmdlet from the pipeline. The criteria given is {$_.Status -eq 'Running'} .

Lets have a look, why " $_.Status " .

PowerShell cmdlets returns output in the form of table(based on Formatting conditions) . We can See Table headrers , Rows , Colums etc .



Here $ is the output from Get-Service cmdlet , $_ represents each row in that output and $_.Status represent a row at a time but only the value for Status . Here " . " represents a fraction of that row.



Finally we got Only running services, PowerShell Parser takes each Row in that Table and will select status for each service then do an IncaseSensitive comparision using operator -eq to mach the string Running.



Friday 16 October 2015

Strings in PowerShell


Like all programming languages, PowerShell uses strings very effectively and provides some interesting capabilities for a script.

PowerShell uses four types of strings.
  1. Single quoted string.
  2. Double quoted string.
  3. Single quoted Here Strings.
  4. Double quoted Here Strings.
PowerShell uses strings as sequence of 16-bit Unicode characters and is directly implemented by system.string .Net type .

Single Quoted Strings
     Single quoted string in PowerShell are nothing, But string which is represented inside single quotes.


    PS C:\ >'This is a Single Quoted string'
    This is a Single Quoted string
    PS C:\ >

    But there is some more about single quoted string,
    lets see this example,

    PS C:\ >'This is a Single quoted $var'
    This is a Single quoted $var
    PS C:\ >
     
    
    Here you can see, I have stored 'String' in a variable named $var , But single quoted string is not able to substitute the value of the $var .
    So we can use single quoted strings where we don't want to substitute a variables value in it.


    Double Quoted Strings.
      Like single quoted strings, Double quoted string are nothing , but Strings included between two double quotes .
      PS C:\ >"This is a Double Quoted string"
      This is a Double Quoted string
      PS C:\ >
      
       
      
      But unlike single quoted strings, Double quoted strings can substitute Values for Variables.
      PS C:\ >"This is a Double quoted $var"
      This is a Double quoted String
      PS C:\ >
      

      Here Strings

      First Lets have a glance on Here Strings.
      Here strings are another way of representing strings , Especially while we have large amount including multiple lines. Here strings are effectively used when generating output for another program. But the same can be achieved regular type of strings which we discussed before.
      Then Why Here Strings ?

      Lets explain it after an example,
      PS C:\ >$HereString=@"
      >>> This is
      >>> An Example
      >>> For
      >>> Here String
      >>> "@
      PS C:\ >$HereString
      This is
      An Example
      For
      Here String
      PS C:\ >
      

      Here we Can see the syntax for here string.

      @"<newline><Strings><newline>"@

      the <newline> is important as strings between the quotes  are treated as Here Strings and the first and last new lines are not included and the main advantage is , we can include single and double quotes regardless the type of Here Strings whether it is single Quoted or Double Quoted.

      Look here on another example,

      PS C:\ >$a='This'
      PS C:\ >$HereString=@"
      >>> $a is
      >>> An "Example"
      >>> For
      >>> 'Here String'
      >>> "@
      PS C:\ >$HereString
      This is
      An "Example"
      For
      'Here String'
      PS C:\ >

      Here the variable is substituted for $a, Single and Double quotes are included too !!!.

      And Single Quoted Here Strings are here strings using single quotes where variables are not substituted with values - @'<newline><string><newline>'@.
      Double Quoted Here Strings are similar, But uses Double quotes instead of single quotes and the variables are substituted here.
      @"<newline><string><newline>"@

      That's all about Strings here... Have fun Using PowerShell

      Saturday 3 October 2015

      TAB completion in PowerShell

       PowerShell: TAB completion in PowerShell

      Reference : PowerShell in Action by Bruce Payette.

      One of the interesting feature in Windows PowerShell is the way of TAB completion. TAB completion in PowerShell allows you to partially enter a command and to hit TAB key to get it expanded cmdlet.

      PowerShell allows you to do TAB completion against file system, If you type part of a filename or path, a TAB completion can easily be done by hitting TAB key. And the interesting thing is doing TAB completion using wildcard '*' .
      C:\ >cd c:\win*ws< tab>
      C:\ >cd C:\Windows
      And PowerShell can do TAB completion on partial cmdlet names too. If you type a part of a cmdlet and then if pressed TAB, it will give you the first matching expanded cmdlet and continues TAB hit will step through to the possible matches.

      We have much more on TAB completion. PowerShell can do TAB completion on Parameters too. Lets see an example.

      C:\ >Get-ChildItem -pa <tab>
      C:\ >Get-ChildItem -Path
      Not only parameters, but on properties too. Have a look on this,
      C:\ >$r="A String"
      C:\ >$r.Len< tab>

      C:\ >$r.Length
      The string "A String" is stored in variable $r and then we check the length of the string using Length property. We use TAB completion here by pressing TAB after entering $r.Leng .

      We Know PowerShell has a
      Get-History cmdlet, Which lists the previously entered cmdlets.
      C:\ >Get-History

      Id CommandLine
         -- -----------
         23 Clear-History
         24 $r="A String"
         25 $r.Length
      Let's do something interesting,
      C:\ >#str< tab>
      C:\ >$r="A String"
      Here we typed #str and hit TAB key , Which returns a previously entered expression that contains 'str' and will step through next matching expression.

      We can get the same using the Id of the previously entered expression.
      C:\ >#24
      C:\ >$r="A String"

      To Explore more about Tab completion in PowerShell, Just go through the built-in  PowerShell function TabExpansion which is editable.



      Monday 14 September 2015

      Creating Aliases


      In the Last Post, I wrote a little about Aliases in PowerShell. So What about creating an Alias.

      Yes we have the option for creating New Alias in PowerShell.And the cmldlet used for Creating aliases in PowerShell is New-Alias.

      So, As Usuall, We Can Go For Get-Help on New-Alias cmdlet.

      PS C:\> Get-Help New-Alias
      
      NAME
          New-Alias
         
      SYNOPSIS
          Creates a new alias.
         
         
      SYNTAX
          New-Alias [-Name] <String> [-Value] <String> [-Description [<String>]] [-Force] [-InformationAction {SilentlyContinue | Stop | Continue | Inquire | Ignore | Suspend}]
          [-InformationVariable [<System.String>]] [-Option {None | ReadOnly | Constant | Private | AllScope | Unspecified}] [-PassThru] [-Scope [<String>]] [-Confirm] [-WhatIf]
          [<CommonParameters>]
         
         
      DESCRIPTION
          The New-Alias cmdlet creates a new alias in the current Windows PowerShell session. Aliases created by using New-Alias are not saved after you exit the session or
          close Windows PowerShell. You can use the Export-Alias cmdlet to save your alias information to a file. You can later use Import-Alias to retrieve that saved alias
          information.
         
      
      Let's look at the Syntax.

      SYNTAX
          New-Alias [-Name] <String> [-Value] <String> [-Description [<String>]] [-Force] [-InformationAction {SilentlyContinue | Stop | Continue | Inquire | Ignore | Suspend}]
          [-InformationVariable [<System.String>]] [-Option {None | ReadOnly | Constant | Private | AllScope | Unspecified}] [-PassThru] [-Scope [<String>]] [-Confirm] [-WhatIf]
          [<CommonParameters>]

      With the help of  this Syntax, Lets create an Alias for a cmdlet. Say Test-Connection.

      Test-Connection cmdlet is used to Test connectivity to one or more remote computers.

      PS C:\> New-Alias -Name TC -Value Test-Connection -Description 'Alias For Test-Connection cmdlet' 

      Here,
      -Name:- Name of the  cmdlet for which we have to create the Alias.

      -Value:- Name of the alias for the cmdlet which we are creating alias.

      -Description:- Description For the New alias of the cmdlet.

      Lets check,

      PS C:\> Get-Alias -Definition Test-Connection
      
      CommandType     Name                                               Version    Source                                                                                        
      -----------     ----                                               -------    ------                                                                                        
      Alias           TC -> Test-Connection                                                 

      Note: Since we Didn't mentioned Version and source info, Those are blank.

      Lets Test The Connectivity to Loopback Adapter.
      PS C:\WINDOWS\system32> Test-Connection 127.0.0.1
      
      Source        Destination     IPV4Address      IPV6Address                              Bytes    Time(ms) 
      ------        -----------     -----------      -----------                              -----    -------- 
      D-113037147   127.0.0.1       192.168.106.1    fe80::bc73:cd7e:5078:531b%15             32       0        
      D-113037147   127.0.0.1       192.168.106.1    fe80::bc73:cd7e:5078:531b%15             32       0        
      D-113037147   127.0.0.1       192.168.106.1    fe80::bc73:cd7e:5078:531b%15             32       0        
      D-113037147   127.0.0.1       192.168.106.1    fe80::bc73:cd7e:5078:531b%15             32       0

      Using Alias,

      PS C:\WINDOWS\system32> TC 127.0.0.1
      
      Source        Destination     IPV4Address      IPV6Address                              Bytes    Time(ms) 
      ------        -----------     -----------      -----------                              -----    -------- 
      D-113037147   127.0.0.1       192.168.106.1    fe80::bc73:cd7e:5078:531b%15             32       0        
      D-113037147   127.0.0.1       192.168.106.1    fe80::bc73:cd7e:5078:531b%15             32       0        
      D-113037147   127.0.0.1       192.168.106.1    fe80::bc73:cd7e:5078:531b%15             32       0        
      D-113037147   127.0.0.1       192.168.106.1    fe80::bc73:cd7e:5078:531b%15             32       0

      We Have succesfully created an Alias for Test-connection cmdlet.

      PS C:\WINDOWS\system32> Get-Alias -name TC|Select-Object Name,Definition,description
      
      Name Definition      Description                     
      ---- ----------      -----------                     
      TC   Test-Connection Alias For Test-Connection cmdlet





      Tuesday 1 September 2015

      About Aliases

      What is an Alias ?
      Alias is an alternate name for an object,Such as Variable,File etc.

      Here in PowerShell, we have somany Aliases which are built-in.And those aliases helps us to run cmdlets fastly, Acting as a time saver.

      Note:Avoid using Aliases in Scripts(Post comes Later).

      So lets take the cmdlet Get-Help again.

      The aliases for Get-Help are help and man. you can see man is a native unix help command,Which shows the manual for a command.

      What about other cmdlets, We have a cmdlet for Getting Alias.
      How to find it, Do it in PowerShell way

      PS>Get-Command -Verb *Get* -Noun *alias*
      
      CommandType     Name                                               Version    Source                                                                                        
      -----------     ----                                               -------    ------                                                                                        
      Cmdlet          Get-Alias                                          3.1.0.0    Microsoft.PowerShell.Utility                                                                  
      
      
      Here we use Get-Command to Find a cmdlet which is Probabbly having Get as Verb and Alias as Noun, We use wild card for reliability.

      so you Got the cmdlet to find Alias is Get-Alias.

      Lets Explore Get-Alias.
      PS>Get-Help Get-Alias
      
      NAME
          Get-Alias
          
      SYNOPSIS
          Gets the aliases for the current session.
          
          
      SYNTAX
          Get-Alias [[-Name] []] [-Exclude []] [-InformationAction {SilentlyContinue | Stop | Continue | Inquire | Ignore | Suspend}] [-InformationVariable 
          []] [-Scope []] []
          
          Get-Alias [-Definition []] [-Exclude []] [-InformationAction {SilentlyContinue | Stop | Continue | Inquire | Ignore | Suspend}] 
          [-InformationVariable []] [-Scope []] []
          
      
      
      Here We got The syntax for Get-Alias.

      Lets find some examples for this cmdlet.
      PS>Get-Help Get-Alias -Examples
      
      NAME
          Get-Alias
          
      SYNOPSIS
          Gets the aliases for the current session.
      
      -------------------------- EXAMPLE 1 --------------------------
       PS C:\>Get-Alias -Definition Get-ChildItem
          
          
          This command gets the aliases for the Get-ChildItem cmdlet.
          
          By default, the Get-Alias cmdlet gets the item name when you know the alias. The Definition parameter gets the alias when you know the item name.
      
      PS>Get-Alias -Definition Get-ChildItem
      
      CommandType     Name                                               Version    Source                                                                                        
      -----------     ----                                               -------    ------                                                                                        
      Alias           dir -> Get-ChildItem                                                                                                                                        
      Alias           gci -> Get-ChildItem                                                                                                                                        
      Alias           ls -> Get-ChildItem                                                                                                                                         
      
      

      So here We got Aliases for Get-ChildItem cmdlet. dir,gci and ls are the Aliases.

      How do we get Built-in aliases.

      PS>Get-Alias
      
      CommandType     Name                                               Version    Source                                                                                        
      -----------     ----                                               -------    ------                                                                                        
      Alias           % -> ForEach-Object                                                                                                                                         
      Alias           ? -> Where-Object                                                                                                                                           
      Alias           ac -> Add-Content                                                                                                                                           
      Alias           asnp -> Add-PSSnapin                                                                                                                                        
      Alias           cat -> Get-Content                                                                                                                                          
      Alias           cd -> Set-Location                                                                                                                                          
      Alias           CFS -> ConvertFrom-String                          3.1.0.0    Microsoft.PowerShell.Utility                                                                  
      Alias           chdir -> Set-Location                                                                                                                                       
      Alias           clc -> Clear-Content                                                                                                                                        
      Alias           clear -> Clear-Host                                                                                                                                         
      Alias           clhy -> Clear-History                                                                                                                                       
      Alias           cli -> Clear-Item                                                                                                                                           
      Alias           clp -> Clear-ItemProperty                                                                                                                                   
      Alias           cls -> Clear-Host                                                                                                                                           
      Alias           clv -> Clear-Variable                                                                                                                                       
      Alias           cnsn -> Connect-PSSession                                                                                                                                   
      Alias           compare -> Compare-Object                                                                                                                                   
      Alias           copy -> Copy-Item                                                                                                                                           
      Alias           cp -> Copy-Item                                                                                                                                             
      Alias           cpi -> Copy-Item                                                                                                                                            
      Alias           cpp -> Copy-ItemProperty                                                                                                                                    
      Alias           curl -> Invoke-WebRequest                                                                                                                                   
      Alias           cvpa -> Convert-Path                                                                                                                                        
      Alias           dbp -> Disable-PSBreakpoint                                                                                                                                 
      Alias           del -> Remove-Item                                                                                                                                          
      Alias           diff -> Compare-Object                                                                                                                                      
      Alias           dir -> Get-ChildItem                                                                                                                                        
      Alias           dnsn -> Disconnect-PSSession                                                                                                                                
      Alias           ebp -> Enable-PSBreakpoint                                                                                                                                  
      Alias           echo -> Write-Output                                                                                                                                        
      Alias           epal -> Export-Alias                                                                                                                                        
      Alias           epcsv -> Export-Csv                                                                                                                                         
      Alias           epsn -> Export-PSSession                                                                                                                                    
      Alias           erase -> Remove-Item                                                                                                                                        
      Alias           etsn -> Enter-PSSession                                                                                                                                     
      

      We have a built-in drive for Aliases !.

      Do  CD tio Alias Drive, And do ls (Get-ChildItem)

      C:\>cd Alias:
      
      Alias:\>ls
      
      CommandType     Name                                               Version    Source                                                                                        
      -----------     ----                                               -------    ------                                                                                        
      Alias           % -> ForEach-Object                                                                                                                                         
      Alias           ? -> Where-Object                                                                                                                                           
      Alias           ac -> Add-Content                                                                                                                                           
      Alias           asnp -> Add-PSSnapin                                                                                                                                        
      Alias           cat -> Get-Content                                                                                                                                          
      Alias           cd -> Set-Location                                                                                                                                          
      Alias           CFS -> ConvertFrom-String                          3.1.0.0    Microsoft.PowerShell.Utility                                                                  
      Alias           chdir -> Set-Location                                                                                                                                       
      Alias           clc -> Clear-Content                                                                                                                                        
      Alias           clear -> Clear-Host                                                                                                                                         
      Alias           clhy -> Clear-History                                                                                                                                       
      Alias           cli -> Clear-Item                                                                                                                                           
      Alias           clp -> Clear-ItemProperty                                                                                                                                   
      Alias           cls -> Clear-Host                                                                                                                                           
      Alias           clv -> Clear-Variable                                                                                                                                       
      Alias           cnsn -> Connect-PSSession                                                                                                                                   
      Alias           compare -> Compare-Object                                                                                                                                   
      Alias           copy -> Copy-Item                                                                                                                                           
      Alias           cp -> Copy-Item                                                                                                                                             
      Alias           cpi -> Copy-Item                                                                                                                                            
      Alias           cpp -> Copy-ItemProperty                                                                                                                                    
      Alias           curl -> Invoke-WebRequest                                                                                                                                   
      Alias           cvpa -> Convert-Path                                                                                                                                        
      



      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 
      
      NAME
          Get-ChildItem
          
      SYNOPSIS
          Gets the items and child items in one or more specified locations.
          
          
      SYNTAX
          SYNTAX
          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>]
      
      

      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

      Verb-Noun
      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.
      [REF]


      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                                    2.0.0.0    FailoverClusters                                                                              
      Alias           Add-WindowsFeature                                 2.0.0.0    ServerManager                                                                                 
      Alias           Apply-WindowsUnattend                              3.0        Dism                                                                                          
      Alias           Begin-WebCommitDelay                               1.0.0.0    WebAdministration                                                                             
      Alias           End-WebCommitDelay                                 1.0.0.0    WebAdministration                                                                             
      Alias           Expand-IscsiVirtualDisk                            2.0.0.0    IscsiTarget                                                                                   
      Alias           Export-DnsServerTrustAnchor                        2.0.0.0    DnsServer                                                                                     
      Alias           Flush-Volume                                       2.0.0.0    Storage                                                                                       
      Alias           Get-GPPermissions                                  1.0.0.0    GroupPolicy                                                                                   
      Alias           Get-ProvisionedAppxPackage                         3.0        Dism                                                                                          
      Alias           Get-VpnServerIPsecConfiguration                    2.0.0.0    RemoteAccess                                                                                  
      Alias           Initialize-Volume                                  2.0.0.0    Storage                                                                                       
      Alias           Move-SmbClient                                     2.0.0.0    SmbWitness                                                                                    
      Alias           Reconcile-DhcpServerv4IPRecord                     2.0.0.0    DhcpServer                                                                                    
      Alias           Remove-ProvisionedAppxPackage                      3.0        Dism                                                                                          
      Alias           Remove-VMFromCluster                               2.0.0.0    FailoverClusters                                                                              
      Alias           Remove-WindowsFeature                              2.0.0.0    ServerManager                                                                                 
      Alias           Set-GPPermissions                                  1.0.0.0    GroupPolicy                                                                                   
      Alias           Set-VpnServerIPsecConfiguration                    2.0.0.0    RemoteAccess                                                                                  
      Alias           Write-FileSystemCache                              2.0.0.0    Storage                                                                                       
      Function        A:                                                                                                                                                          
      Function        Add-BCDataCacheExtension                           1.0.0.0    BranchCache                                                                                   
      Function        Add-BgpCustomRoute                                 2.0.0.0    RemoteAccess                                                                                  
      Function        Add-BgpPeer                                        2.0.0.0    RemoteAccess                                                                                  
      Function        Add-BgpRouter                                      2.0.0.0    RemoteAccess                                                                                  
      Function        Add-BgpRoutingPolicy                               2.0.0.0    RemoteAccess                                                                                  
      Function        Add-BgpRoutingPolicyForPeer                        2.0.0.0    RemoteAccess                                                                                  
      Function        Add-BitLockerKeyProtector                          1.0.0.0    BitLocker                                                                                     
      Function        Add-DAAppServer                                    2.0.0.0    RemoteAccess                                                                                  
      Function        Add-DAClient                                       2.0.0.0    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.

      Get-Verb




      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
      98





      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 ?

      Type 
      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.

      SYNTAX
          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.

      DESCRIPTION
          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
      10

       
      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
      1024
       
      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

      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.