Sunday, April 15, 2012

PowerShell Quick Reference for SharePoint Administrators

What is PowerShell?
PowerShell is a command-line scripting tool that helps you to automate and quickly solve tedious Administrator tasks. It was originally developed by Microsoft for task automation and configuration management purposes. PowerShell combines the Power of command-line shell and scripting language!

PowerShell also provides an administrator full access to COM, WMI and supports API calls from several applications, Such as:

  • SharePoint
  • Exchange Server
  • Windows Desktop OS, Server OS
  • SQL Server
  • SCOM/SCDPM/SVCMM
  • VMWARE/Citrix 
  • Office 365, Azure, etc.
PowerShell runs on top of .NET framework, 2.0+. With PowerShell, we can automate almost every thing we do with GUI (some times, things which are not possible with GUI). Its not just command prompt or Script language, But its a Command-Shell, just like DOS shell, But more powerful.

Problems with Existing scripting languages
  1. No common scripting for all the products
    • .Net code
    • COM Model
    • Exe
    • VBScript
  2. Scripts are really security concern, because they do have lot of power
    • Echo “Welcome”
    • Del *.* ???
  3. Top Concerns:
  • Integrity
  • Identity
  • Double click Run
  • Command Hijacking
PowerShell addresses this issue by introducing Executing Policy

PowerShell’s Execution Policy
  1. Restricted - No scripting allowed
  2. Unrestricted - You can any scripting
    • No signing required
  3. Remote signed – good for Test, Dev environments
    • Only files from internet need to be signed
    • This is the default setting
  4. All signed  - local, remote script, it should be signed.
    • user must agree to run script
To change the Execution Policy you can execute the Set-ExecutionPolicy RemoteSigned  from PowerShell command window. This in fact sets the registry key: HKLM\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell

IDEs:
  1. ISE – PowerShell 2.0, built-in. you can fire it by typing PowerShell_ISE in run box!
  2. PowerGUI - Open source yet powerful, I Love it! FREE.
  3. Powershell +
Cmdlets
Cmdlets are built-in commands for PowerShell. Heart and Soul of PowerShell or Engine that make PowerShell work. They are the small units of functionality that perform the operations. will be in
"verb-noun" names.
E.g.  Get-Childitem
   Get-help
       Get-Command  - Lists all available cmdlets

Cmdlets are extensible. We can write own cmdlets.

Basic Tour: Help, Process, Services & Event log:
Getting help in PowerShell
E.g.
Get-Help
Get-Help –verb get
Get-Help –noun file
Get-help  stop-process –examples
Get-help  stop-process –full
Get-help SP*

Basic cmdlets for process, services
Ask for Help: Help *process*
E.g. Get-process –name calc
Get-process  can be called by its Alias PS

How to get the available properties & methods of a cmdlet?
Use: Get-process | get-member
Stop-process -> Alias Kill
Stop-process –name calc
Stop-process –name calc –whatif

Services Cmdlets
Get-service <service name>
Restart-service <service name>
Stop-service <service name>
Get-service –include “Sharepoint*”
Get-service –exclude “Sharepoint*”

Event log: 
Get-eventlog
Eg. get-eventlog system –newest 10
Get-eventlog | -newest 10 format-list


Variables
PowerShell assigns best suited data type for variables when assigned. Variables start with $ sign.
New-variable  -name var –value 10
Remove-Variable –name var

Or
$var=10

PowerShell Supports Int, DateTime, Bool, String, Char, Byte, decimal, array, XML data types. Variables are actually .net objects.
$Test="Crescent"
We can use $Test.toUpper() to get the upper case of the string $Test. Use Get-Member to retrieve all the member of the object. If you have to force the data, you can use:[string]$var=5
$var.gettype().fullname

Variables Can be strongly typed. E.g.
[string]$text = "Text Value goes here" 


Boolean/Null variables:Set a Variable to: true
$Completed = $true

To Check if a Variable is true
If ($completed -eq $true)
{
  #Do something
}

Check for Null:
If ($Completed –eq $null)
{
  #Do something
}

Pipelines
Commands manipulates and passes objects from One to another
 E.g: Get the list of process > filter > stopped Process > format the output to screen
Get-process | where-object {$_.status –eq “Stopped”} |format-list
Get-process | out-file C:\process.txt
Get-process | out-Printer <Name of the printer>

Read/Write to Screen:

Write-Host "Hello World!" –foregroundcolor "green"

$name = Read-Host "Enter your name"
Write-Host "Hello" $name


Write-output Vs write-host
First one sends output to the pipeline, Second doesn’t
Write-output “Hello” |where-object {$_.length – gt 2}
We have some additional options like –foregroundcolor


Operators
All Basic math operations: +, -, *, /, %
5+5; 10-1; 8*2; 10%3; 5+(5*5)

Comparison:
Comparison operators list:
-lt Less than
-le Less than or equal to
-gt Greater than
-ge Greater than or equal to
-eq Equal to
-ne Not equal to
-like Like (uses wildcards for matching)
-notlike Not like (uses wildcards for matching)

Equal to: EQ
Not Equal to: NE
10 –eq 5
LT, -GT, -GE, -LE
String comparison: not case sensitive
“Hello” – eq “HELLO” > true
Forcing case sensitive:
“Hello” – ceq “HELLO” > true
Logical operators
AND OR NOT

Sort – Measure –Select - Compare- filter
Sort
Get-process | sort-object VM –desc
Get-service |sort status
Measure
Get-service |measure-object
Get-service |measure-object –property VM –sum –min-max –average
Select
Get-service | select-object displayname,status
Get-process | select-object –first 10
Compare:
$p1=get-process
Now open a new process, say calc
$p2=get-process
Compare-object $p1, $p2 –property name

Export-Import and compare
Export-CSV
Get-process | Export-csv
Import-CSV
$Process=import-csv c:\sa.csv

Logical constructs

IF, Switch, For, While
IF, Switch – Decision. For, while – looping

if($var –gt 100)
 { 
  write-host “yes”
 }
  elseif()
  {
   //do something
  }
  else
 {
  //do something else
 }

Switch
E.g.

$company =“Crescent”
Switch($var)
{
“Microsoft” {write-host “Microsoft”}
Crescent” {write-host “Crescent”}
Default {write-host “Not in list”}
}


While, Do..while, Do.. Until:
$var=1
While($var – lt 10)
    {
        write-host $var
        $var++
    }
 
Do-While:
$a=1
Do {$a; $a++}
While($a –lt 10)


Do-Until:
$a=1
Do {$a; $a++}
Until($a –gt 10)


For-each
$services=Get-Service
Foreach($x in $services)

   write-host $x.name.ToUpper()
}

For-Loop:
For ($i=1; $i -le 10; $i++)
{
    write-host $i
}


Script Block
Executes the block of code from file, variable
$b={write-host “Hello”}
$b >>write-host “hello”
To Execute : &$b

Functions:

E.g.  
Function sayHello()
{
  write-host “Hello”
}
sayHello
 
E.g. 
Function sayHello($SenderName)
{
  write-host “Hello” + $senderName
}
sayHello “Crescent

SayHello “Crescent” -> write-host “Hello” $args[0]

Return statement:
function determine
{
 if($var – gt 10)
 {
  return $true
  }
  Else
  {
  return $false
  }
}

Comments:
Single line comment : #comment
Multi-Line:
<#
Multiline Comments
Can be placed inside
comment block
#>

Regular expressions
 Regular expressions is the standard for Pattern matching. In PowerShell we have to use –Match
E.g.
  •  “Crescent” –match “Honey”
  • . (dot) – one char
  • * - Zero or more match   “A” match “t*”
  • + - one or more match “TTT” match “^T+”
  • ? – Zero or one match
  • [AB] – either A or B
  • ^ - start
  • $ - end  eg. “Sala” –match “^s..A$”
  • \w – any word character  -W –Non word
  • \s – space    -S
  • \d   -D
  • (n,m) eg. “TTTT” –match “^T{4, 6}”

Strings, Arrays, Hash tables 
$H="Crescent"
$H.length
To Say “hello”: “Say “”hello”””
 

Array:  
$arr=1,2,3  or $arr=@(1,2,3)
To Get: $arr[0]
$arr2=@((1,1),(2,2),(3,3))
Get : $arr2[1][1]

Hash Table:
 
$Hash=@{No=1;CName="Crescent"}
$hash.no
$hash["Cname"]
 

XML handling: Read XML
 $MyXML=[XML] @”
<addressBook>
<Person type=“personal”>
<name>ABC</name>
<Phone>123</phone>
</person>
</addressbook>
“@
$myXML.AddressBook
$myXML.Person
$myXML.Person[0]


 
Getting Started with SharePoint PowerShell:
PowerShell contains hundreds of commands, which are called cmdlets. These application specific cmdlets usually warped to the "Snap-ins". So, to use SharePoint cmdlets in PowerShell, You need to add the SharePoint PowerShell snap-in first.

Tip: You can use "SharePoint 2013 Management Shell" which loads the SharePoint snapin into PowerShell by default!

To start with, Add PowerShell snapin to your script as the first line:
Add-PsSnapin Microsoft.SharePoint.PowerShell

Now you can use PowerShell to interact directly with SharePoint Web Applications, Site collections, Sites, Lists ,etc.

E.g. Get-SPSite -identity "http://sharepoint-site-url"

However, if you try to run your script again, you'll get an error saying:
Add-PSSnapin : Cannot add Windows PowerShell snap-in Microsoft.SharePoint.Powershell because it is already added. Verify the name of the snap-in and try again.
To mitigate use either:
if((Get-PSSnapin | Where-Object {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) 
{ 
    Add-PSSnapIn "Microsoft.SharePoint.Powershell" 
}
or
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

Introduction to PowerShell ISE:
Here are the steps to launch PowerShell ISE.
  • Go to Start >> All Programs >> Accessories >> Windows PowerShell >> Windows PowerShell ISE

 
 
Resources:
http://blogs.msdn.com/powershell
http://thepowershellguy.com
http://keithhill.spaces.live.com
http://www.leeholmes.com/blog
PowerShell Installation Instructions: http://shrinkster.com/rpy
PowerTab by MoW - http://shrinkster.com/rpx
“MSH Logo” by Lee Holmes - http://shrinkster.com/rpw
PowerShell Community Extensions: http://www.codeplex.com/PowerShellCX
MSDN - http://shrinkster.com/rpu
How to create a cmdlet: http://shrinkster.com/rpv

PowerShell Team Blog - http://blogs.msdn.com/powershell/
Lee Holmes - http://www.leeholmes.com/blog/
David Aiken - http://blogs.msdn.com/daiken/
The PowerShell Guy (MoW) - http://thepowershellguy.com/



You might also like:
SharePoint Usage Reports
Usage reports, collaboration and audit for SharePoint.
Document SharePoint Farm
Automatically generate SharePoint documentation.
*Sponsored


Check out these SharePoint products:

No comments :

Post a Comment

Please Login and comment to get your questions answered!

You might also like:

Related Posts Plugin for WordPress, Blogger...