Saturday, February 4, 2012

Difference between Cmdlet and PSCmdlet

As taken from MSDN:


Cmdlet Base Classes

Windows PowerShell supports cmdlets that are derived from the following two base classes.
  • Most cmdlets are based on .NET Framework classes that derive from the Cmdlet base class. Deriving from this class allows a cmdlet to use the minimum set of dependencies on the Windows PowerShell runtime. This has two benefits. The first benefit is that the cmdlet objects are smaller, and you are less likely to be affected by changes to the Windows PowerShell runtime. The second benefit is that, if you have to, you can directly create an instance of the cmdlet object and then invoke it directly instead of invoking it through the Windows PowerShell runtime.
  • The more-complex cmdlets are based on .NET Framework classes that derive from the PSCmdlet base class. Deriving from this class gives you much more access to the Windows PowerShell runtime. This access allows your cmdlet to call scripts, to access providers, and to access the current session state. (To access the current session state, you get and set session variables and preferences.) However, deriving from this class increases the size of the cmdlet object, and it means that your cmdlet is more tightly coupled to the current version of the Windows PowerShell runtime.

SwitchParameter


I was curious how one can create his own cmdlet, with parameters which do not take values.
For example, when a Cmdlet runs, we can specify -Verbose. This parameter does not take a value, it simply exists.

We do this by creating a parameter like this.

    private SwitchParameter hasHeader;
    [Parameter(Position = 1,
    Mandatory = false,
    ValueFromPipelineByPropertyName = true,
    HelpMessage = "Whether first row is a header"),
    ValidateNotNullOrEmpty()]
    public SwitchParameter HasHeader { 
              get { return hasHeader; } 
              set { hasHeader = value; }
      }

And then we check for it like this:

if (HasHeader.IsPresent){ };

It is important to note that the default value is false.

Delete a service from Services.Msc

Sometimes you want to delete a service from the Services.Msc, and you do not have access to the uninstaller.

In this case, you can use the command prompt to delete such a service.

Simply open the Command Prompt (CMD.exe)
And insert the followign command sc delete NameHere. 
You can find the name from Services.msc.

Typical pipeline cmdlets and functions


  • Cmdlet/Function         Description

  • Compare-Object         Compares two objects or object collections and marks their differences
  • ConvertTo-Html           Converts objects into HTML code
  • Export-Clixml             Saves objects to a file (serialization)
  • Export-Csv                 Saves objects in a comma-separated values file
  • ForEach-Object          Returns each pipeline object one after the other
  • Format-List                Outputs results as a list
  • Format-Table              Outputs results as a table
  • Format-Wide              Outputs results in several columns
  • Get-Unique                 Removes duplicates from a list of values
  • Group-Object              Groups results according to a criterion
  • Import-Clixml              Imports objects from a file and creates objects out of them (deserialization)         
  • Measure-Object          Calculates the statistical frequency distribution of object values or texts
  • more                          Returns text one page at a time
  • Out-File                      Writes results to a file
  • Out-Host                    Outputs results in the console
  • Out-Host -paging         Returns text one page at a time
  • Out-Null                      Deletes results
  • Out-Printer                  Sends results to printer
  • Out-String                   Converts results into plain text
  • Select-Object              Filters properties of an object and limits number of results as requested         
  • Sort-Object                 Sorts results
  • Tee-Object                  Copies the pipeline's contents and saves it to a file or a variable
  • Where-Object              Filters results according to a criterion

Good free Powershell book

I am currently reading this book about Powershell. It has some good examples, and very detailed explanations of how Powershell works.

Wednesday, February 1, 2012

Powershell Aliases

An Alias is simply a different way of doing the same task. So if you are used to other systems (e.g. CMD or Linux), you can most likely migrate that task. Below is a list of such tasks.


If the alias you wish does not exist, no problem. Here is how to create your own.

Set-Alias [-Name] [-Value]

If you want to see what Aliases you have set,

Get-Alias [[-Name] ]


PowerShell (Cmdlet)

PowerShell (Alias)

Get-ChildItem

gci, dir, ls

Get-Content

gc, type, cat

Get-Command

gcm

Get-Help

help, man

Clear-Host

cls, clear

Copy-Item

cpi, copy, cp

Move-Item

mi, move, mv

Remove-Item

ri, del, erase, rmdir, rd, rm

Rename-Item

rni, ren, mv

Get-Location

gl, pwd

Pop-Location

popd

Push-Location

pushd

Set-Location

sl, cd, chdir

Tee-Object

tee

Write-Output

echo, write

Get-Process

gps, ps

Stop-Process

spps, kill

Select-String

n/a

Set-Variable

sv, set




Searching for text files using Powershell

Below, one can admire the simplicity, power, and flexibility of Powershell.

Here are two ways of searching for all textfiles in your C Drive.

  • Get-Childitem C:\ -recurse -force | Foreach { IF ($_.extension -eq ".txt") { $_.name } }

  • Get-ChildItem C:\ -recurse -force | Where { $_.extension -eq ".txt" } | select $_.name

How to run a Powershell script, without closing the console.

As taken from here.

Powershell.exe -noexit C:\Scripts\Test.ps1

There are actually three parts to this command:

  • Powershell.exe, the Windows PowerShell executable.

  • -noexit, an optional parameter that tells the PowerShell console to remain open after the script finishes. Like we said, this is optional: if we leave it out the script will still run. However, the console window will close the moment the script finishes, meaning we won’t have the chance to view any data that gets displayed to the screen.

    Incidentally, the -noexit parameter must immediately follow the call to the PowerShell executable. Otherwise the parameter will be ignored and the window will close anyway.

  • C:\Scripts\Test.ps1, the path to the script file.

How to run scripts from within Powershell

As taken form here.

To summarize, here’s how you run from scripts from within Windows PowerShell:

  • Make sure you’ve changed your execution policy. By default, PowerShell won’t run scripts at all, no matter how you specify the path.

  • To run a script, specify the entire file path, or either: 1) use the .\ notation to run a script in the current directory or 2) put the folder where the script resides in your Windows path.

  • If your file path includes blank spaces, enclose the path in double quote marks and preface the path with an ampersand.

Tuesday, January 31, 2012

PowerShell

Recently, I have been playing with Powershell, which is an incredibly powerful tool. Below is a very good summary of it, from http://blogs.msdn.com/b/powershell/archive/2007/05/11/free-powershell-book.aspx


With Windows PowerShell (previously Monad Shell, MSH) the software group administrators want to give us a shell under Windows that we can use to write as many scripts as our hearts desire in order to control our systems. Windows PowerShell follows a completely new concept than that used by text-oriented shells such as Bash. Aims of developing Windows PowerShell Windows PowerShell is a new Windows command line shell that was specifically developed for system administrators. The shell consists of an interactive input line and script environment that can be used either alone or in combination. In contrast to most shells that accept and return text, Windows PowerShell is based on an object model made available by .NET Framework 2.0. This fundamental change in the environment allows for completely new tools and methods for managing and configuring Windows. Windows PowerShell introduces the idea of cmdlets (pronounced “commandlet”).
A cmdlet is a simple command line tool that is integrated into the shell and executes a single function. Although you can use cmdlets in isolation, their power is more obvious when used in combination to perform complex tasks.

Stored Procedure to Query Metadata

One must not forget that at the end of the day, databases store all metadata internally in a way which can be queried.

Therefore, in MS SQL, one can use the following query to search within stored procedures.

SELECT ROUTINE_NAME, ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%Reuben%'
AND ROUTINE_TYPE='PROCEDURE'

This query is used to search all stored procedures, which have the word Reuben within them.