Sharing the experience search

Search sharing-the-experience.blogspot.com
Showing posts with label PowerShell. Show all posts
Showing posts with label PowerShell. Show all posts

Wednesday, October 9, 2013

SharePoint Online and PowerShell: How to Get-Spweb?

Finally, your SharePoint is Online! I mean, you have got your farm running in SharePoint online.

You still have some administration\development\maintenance left for SharePoint Online. And of course, the main means that you have used to have to do your job is PowerShell.

Now, tricky questions (who thought!) - how do you run Get-Spweb in SharePoint Online?

Isn't true that we have PowerShell in SharePoint online, you might wonder?
Yes, you are right (kind of), we have SharePoint Online management shell.
But, the module microsoft.online.sharepoint.powershell only includes some basic manipulation commands on the site collection level 

Check this cool visual tool for PowerSheeling in SharePoint to see what's available in SharePoint PowerShell modules.

So, how do you proceed with the task Get-Spweb in SharePoint Online?
Through SharePoint Client Side model of course!

Here are 3 ways that deal with it:
1.Gary Lapointe module - Lapointe.SharePointOnline.PowerShell.msi
Example:
Get-SPOWeb [-Detail [<SwitchParameter>]] [-Identity [<SPOWebPipeBind>]]

2. Using standard  Microsoft.SharePoint.Client dll

Example:

$loadInfo1 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
$loadInfo2 = [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
$webUrl = Read-Host -Prompt "HTTPS URL for your SP Online 2013 site" 
$username = Read-Host -Prompt "Email address for logging into that site"
$password = Read-Host -Prompt "Password for $username" -AsSecureString


$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($webUrl) 
$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)
$web = $ctx.Web
$webs = $web.Webs
$lists = $web.Lists 

$ctx.Load($lists)
$ctx.Load($webs)
$ctx.Load($web)
$ctx.ExecuteQuery()

$lists| select -Property Title



Example:

#You need to run PowerShell in single-threaded mode (the authentication requires it).
powershell -STA
#Import the DLL.
[Reflection.Assembly]::LoadFile("{local path to the dll ClaimsAuth.dll}")
#Instantiate a new SPOContext providing your SharePoint Online site URL. (Don’t forget the https)
$ctx = new-object SPOContext("{Url of the site}")

#let's test it

$web = $ctx.Web
$lists = $web.Lists 

$ctx.Load($lists)
$ctx.Load($web)
$ctx.Load($web.Webs)
$ctx.ExecuteQuery()

$lists| Select -Property Title, ItemCount | FT -AutoSize

Now, it's finally is THE TIME, SharePoint Online Administators, to get know Client Side Object Model for SharePoint! 

Friday, July 19, 2013

SharePoint 2010 to 2013 Upgrade: Phase I "Cleaning". Unused spweb

As you may know Microsoft recommends to clean the farm first before migrating to a new version of SharePoint. (Clean up an environment before an upgrade to SharePoint 2013)

For my migration story SharePoint 2007 to SharePoint 2010, please refer to "SharePoint 2007 to 2010 Upgrade" online project


Now, I m in the process of migration SharePoint 2010 to SharePoint 2013.
I recommend to start cleaning from top to bottom.
First, check unused web applications - SharePoint 2010 to 2013 Upgrade: Phase I "Cleaning". Unused web applications




And finally, let's check what sites (spweb) are not in use

I took following principle to identify unused sites - if the site doesn't have content except the standard one ( ex: Master Page Gallery, one item in Announcements), it's considered an unused site.

To check the content , or to say more specifically, the itemcount in every list in the site, I use this PowerShell  script:

$rootSite = Get-SPSite  {site collection url}                                                                                                                                                                                                     
$rootSite.AllWebs | foreach {  $_.Lists | Select ParentWebUrl, Title, ItemCount |Sort ItemCount -Descending } |Export-Csv webs_content.csv

Once I have got data in the the file, I have created a simple pivot table to check sum of the items per site:
That gives me to determine which site doesn't contain user data (in my case the site the contains only 4 items:
default Announcement, and 3 items in the Master Page Gallery) 
And finally, delete unused sites:

$rootSite = Get-SPSite  {site collection url}                                                                                                                                                                                                       
$sitesToDelete = "{spweb relative url}";

foreach ($site in $sitesToDelete)
{
  $spweb = $rootSite.AllWebs[$site];
  $spweb.Name
  $spweb.Lists| group ItemCount -AsHashTable
  $spweb.Delete()
  $spweb.Dispose()
  "Web is deleted"
}

Friday, September 14, 2012

Term store migration to another farm

Your task is to migrate a content db to another farm. For this you can refer to the post How restore a SharePoint 2010 content database on the different farm

But in case you have managed metadata column somewhere in your web application, you will soon discover that they lost related term set which is expected.

The term store is not stored in the content database. It's a responsibility of the Managed Metadata Service.

You question - how can I migrate term store from one farm to another?

Here is what I found useful to read and use:

Migrating managed metadata term sets to another farm on another domain - the article clearly explains what happens with metadata value in the columns when you restore content db on the another farm. Essentially, you will not loose metadata value in the lists, but you can't use it further until you migrate related term store.

Article also provides a means to migrate your term set and how do you reconnect the term store to the content via PowerShell - http://sptermstoreutilities.codeplex.com/


Here is my 2 cents in it:

Instead of using http://metadataexportsps.codeplex.com/ for UI export\import of term store, you can use a PowerShell from Laponte - a PowerShell SharePoint guru - Exporting and Importing SharePoint 2010 Terms. The navigation on his blog  is a little bit confusing - the extended powershell comands are bundled in one Lapointe.SharePoint2010.Automation.wsp on http://blog.falchionconsulting.com/index.php/downloads/

In case you want to know how to use PowerShell in SharePoint -Simple concept: How to use SharePoint cmdlets in PowerShell ISE


ATTENTION:
If you have reused terms in the termset, make sure the order in the export file the following:
Parent, then Child
In this example, the term set Customers reuse terms from the first level of the term set Projects. In the initial file that I have exported, the customer set goes first before the project.
If I try to export this file via Import-SPTerms , I will get an error.
I need to change the order of the terms beforehand and them import the file.


P.S.

For SPOnline migration I believe you have only one option is to export via csv . I wonder what about exporting reused terms. I can't see the int csv file to specify it....

Friday, June 22, 2012

SharePoint: SharePoint 2007 Administration and PowerShell 2.0



Last months my work with SharePoint 2007, I felt a strong inclination to use PowerShell 2.0.
I envied a happy people who were already with SharePoint 2010 and could enjoy SharePoint 2010 Administration via SharePoint.ps1


PowerShell and SharePoint: What, Why and How
Simple concept: How to use SharePoint cmdlets in PowerShell ISE


I also wanted to have such beautiful commands that have been shipped by SharePoint.ps1 for SharePoint 2010:
Get-SPFarm,
Get-SPWeb,
Get-SPWebApplication


So, my problem was that we don't have SharePoint.ps1 for SharePoint 2007.
To easy up my desire, I have created my functions:
Get-SPFarmV3,
Get-SPWebV3,
Get-SPWebApplicationV3.


And some additional:
Get-SitesWithMissingTemplate, Get-SSProvider, Get-SPVersionV3.


All above I have packed in one SPv3Adapter.mdl module.


Windows PowerShell Module Concepts


Module Installation Best Practices:


Do not install modules for Windows PowerShell in the system location at %Windir%\System32\WindowsPowerShell\v1.0\Modules. Only modules included with Windows are installed to the system location.


http://msdn.microsoft.com/en-us/library/dd878350(v=vs.85).aspx


Module installation
http://msdn.microsoft.com/en-us/library/dd878350(v=vs.85).aspx




And some additional PowerShell files:
Helper functions: Start-CustomTranscript, Get-CustomAPPLog,Get-SolutionDeployed


I have used a lot Get-SolutionDeployed during upgrade SP2007 to SP2010:


The module Helper.mdl has dependency on SPv3Adapter.mdl

Please install  SPv3Adapter.mdl  module first in order to enjoy Sp2007 helper functions.
One of the favorable option for me is to use manifest (you are welcome to use attached customModulesLoader.psm1 and  Manifest.mdl)  to ship the PS modules.


Tuesday, June 19, 2012

SharePoint : Farm solution deployment with no downtime. Update-SPSolution -local

Wondering if it's possible to re-deploy farm solution wsp file without downtime? 

In some circumstances, it's possible.


You can do no-downtime deployment if following is true:
 - Your modified wsp file doesn't contain new files or features. The most common scenario, you want to change some code logic that is an existing dll. Once you deploy your modified wsp, the new dll will be placed in GAC (in case you don't have versioning enabled).


- You have load-balanced WFEs. (ISA with SharePoint Farm ( a little bit more complicated scenario with off-box SSL termination))



Here is how it works:
1. ISA test.
Test first if site is up with one server drained. Test for all severs in the ISA farm object for portal.

2. ISA switch.
Drain the first WFE.

3. WFE work. Update-SPSolution
Copy new wsp file on the local drive.
Run
Update-SPSolution -Identity {name}.wsp -LiteralPath "{path}\{name}.wsp" -Local –GACDeployment

Make sure that you specify the parameter –local.
It will deploy files locally and locally restart IIS.

After such update you will see following:


I have 2 boxes in QC env: SOA-MOSS01-QC, SOA-MOSS02-QC.
In the last operation result I see that operation is been performed only on one box SOA-MOSS01-QC.
The second box haven’t been updated yet and at this time actively  serving user requests with old functionality in place.

NOTE:

The Update-SPSolution cmdlet upgrades a deployed SharePoint solution in the farm. Use this cmdlet only if a new solution contains the same set of files and features as the deployed solution. If files and features are different, the solution must be retracted and redeployed by using the Uninstall-SPSolution and Install-SPSolution cmdlets, respectively.

Uninstall-SPSolution also has –local parameter.
But, The Install-SPSolution cmdlet deploys an installed SharePoint solution in the farm. Use the Add-SPSolution cmdlet to install a SharePoint solution package io the farm.
I haven’t tested this option.  And I can see a caveat here, if we need to add-spsolution , we need to remove-spsolution first. And this command doesn’t have –local option. Most likely in the scenario when we need to re-install spsolution instead of update, we have to bring the portal down.

4. Test the result locally on that drained and already updated WFE.

5. ISA Switch
Re-switch the servers.

6. Repeat steps from 3-4.

Done.

P.S.
That is how it looks from an end-user:
He is still accessing the portal while the specific WFE IIS is down.



Wednesday, June 13, 2012

Simple Concept: How to export wsp file?

[Question]: How can I export wsp file from farm solution?

[Answer]:
User PowerShell script:
PowerShell Script for SP2010 to export farm solution file




SharePoint: Administrators audit. How to pull all farm and site collections administrators

Finally, get a chance to write something ... in code! not in the paper sketching the meeting, not an email, not a post)

The current client wants to have information on administrators of the farm: Farm Administrators, Site collections administrators.

One of the option, to go and check manually it.

But, we want to have instant report at this moment, who is an admin of what in the SharePoint farm.

I have written a PowerShell script for SharePoint 2010 to pull Farm Administrators and Site Collections Administrators into XML report.

The report looks like this:



You are free to download it from TechNet Script Center Repository

Tuesday, March 27, 2012

Simple concept: SharePoint 2010 Visual Upgrade Powershell

[Question]:

How do I visual upgrade 2010 my all 2007 web sites using PowerShell?

[Answer]:

 Get-Spsite -Limit All | % { $_.VisualUpgradeWebs() }


In case you need to revert changes:


$web = Get-SPWeb "{your spweb url}"
$web.UIVersion=3
$web.Update()


Further reading:

Simple concept: How to use SharePoint cmdlets in PowerShell ISE [Question]:

The source on inspiration: Automating SharePoint 2010 with Windows PowerShell 2.0  

Friday, March 9, 2012

Simple concept: How to create site collection with different content database?

[Question]:
How to create a site collection that uses new content database?

[Answer]:
Here is a PowerShell script how to do it:


$webAppUrl = "{your web app url}"
$contentDBName="{new content db name}"
new-spcontentdatabase -name $contentDBName -webapplication  $webAppUrl -DatabaseServer "{your sql server for content Dbs}"

$db = get-spdatabase | where {$_.Name -eq $contentDBName}  
$db.AddFailoverServiceInstance("{your failover server}");
$db.Update()

new-spsite -name "{site collection anme}" -ContentDatabase $contentDBName -url "{site collection url}" -OwnerAlias "{domain\user to be a primary site collection administrator}"


For further reading:

1.  Here is my favorite Russian blogger who shares his wisdom on "Tips to create a Site Collection in new Content Database"

2. My post on Failover option in SharePoint 2010

3. New-spsite without parameter Template will create a root web for the site collection. The url of site collection will give you a blank page, and you are free to create any sites (spwebs) under the site collection.

 A small tip for newbie: you can get to the root web site collection properties through url : {your new site collection created without template}/_layouts/settings.aspx

Monday, January 30, 2012

BDCM: How to import through PowerShell

[What you have]:
You have a bunch of BDCM files.

[What you want]:
You want to import BDCM files via PowerShell Script.

[What you want to know]: 

[What you want to do]:
Run following in your PowerShell window:

sl {your path to BDCM files}


$MetadataStore = Get-SPBusinessDataCatalogMetadataObject -BdcObjectType "Catalog" -ServiceContext {your url to CA}


$bdcmFiles = @(Get-ChildItem);
foreach ($bdcmFile in $bdcmFiles)
{


Import-SPBusinessDataCatalogModel -Path $bdcmFile.Name -Identity $MetadataStore -Force


}


[What you want to consider]:


BDCM: How to set permissions through the code?

Friday, December 9, 2011

Simple Concept: PowerShell: The local farm is not accessible.

[Question]: What permissions should I have to run PowerShell against SharePoint 2010?
How can I fix following issues:
 - The local farm is not accessible. Cmdlets with FeatureDepedencyId are not registered
 - Cannot access the local farm
 - Object reference not set to an instance of an object?




[Answer]:
Remember, when using the SharePoint 2010 Management Shell and its Windows PowerShell cmdlets, you need both:


  the rights  granted via the Add-SPShellAdmin cmdlet and 


 local administrator rights on the server on which you’re running the management shell


(From Hey, Scripting Guy! Tell Me About Permissions and Using Windows PowerShell 2.0 Cmdlets with SharePoint 2010)

P.S. Do you need a fast tour on PowerShell And SharePoint 2010?

PowerShell and SharePoint: What, Why and How - gives you an overview what's PowerShell and how to use it for SharePoint 2010

SharePoint 2010: PowerShell and Stsadm - explains why you want to use PowerShell instead of stsadm in SharePoint 2010

Simple concept: How to use SharePoint cmdlets in PowerShell ISE - shows you how to user PowerShell in SharePoint 2010

PowerShell: Add-SPSolution -force when wsp is already deployed - a PowerShell replacement for stsadm -o addsolution and deploysolution

Tuesday, November 29, 2011

Simple concept: How to use SharePoint cmdlets in PowerShell ISE

[Question]:
I heard that I can manage everything in SharePoint 2010 with PowerShell. But when I run Windows PowerShell ISE , it doesn't recognize SharePoint PowerShell commands (ex: Get-SPContentDatabase)

How can I use PowerShell ISE for SharePoint 2010?

[Answer]:
 SharePoint 2010 Management Shell is a just a PowerShell instance that loads sharepoint.ps1 script. So, you are free to use your own favorite IDE to build scripts, just load sharepoint.ps1 (SharePoint 2010: PowerShell and Stsadm)

To get sharepoint.ps1 loaded in PowerShell ISE:

1. Start PowerShell ISE

2. (in case you haven't created a profile yet)
run the following command to create a profile which loads every time you start PowerShell ISE
new-item -path $profile -itemtype file -force 

3. (in case your profile is empty)
the following command writes to profile "." source loading of SharePoint.ps1"

sc  $profile  “.'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\CONFIG\POWERSHELL\Registration\SharePoint.ps1'”

OR use more universal approach which doesn't depend on the SP version (whether it's 14 or 15 (2010 or 2013))

sc  $profile "Add-PSSnapin 'Microsoft.SharePoint.PowerShell'"

4. Restart PowerShell ISE

P.S. In case you don't know where to get PowerShell ISE: PowerShell and SharePoint: What, Why and How

Simple concept: Database is up to date, but some sites are not completely upgraded.

[Question]:
After Mount-SpcontentDatabase, I m having Database is up to date, but some sites are not completely upgraded. on /_admin/DatabaseStatus.aspx. When I click on the /_admin/UpgradeStatus.aspx it shows me the status - Succeeded


How can I know what site collection is not upgraded and how can I upgrade it?


[Answer]:
First of all, to identify what site collection doesn't got upgraded, run:


stsadm.exe -o localupgradestatus > upgradestatus.txt


Open upgradestatus.txt and scroll down to the end of the file, you will see similar section:
In this picture as you see, there no site collection that need upgrade.
If you have any, you can identify them by searching by word "Needs upgrade" in this file.

Secondly, run the command in the PowerShell:


$id=(Get-SPContentDatabase -Identity "{Your content db name}").Id
Upgrade-SPContentDatabase -id $id

Finally, check the upgrade status by running stsadm again:
stsadm.exe -o localupgradestatus > upgradestatus.txt


In my case, it helped me get rid of the site collection "Needs update" warning in the report generated by stsadm.exe -o localupgradestatus


P.S. But still, I am having Status "Database is up to date, but some sites are not completely upgraded." which doesn't bother me since localupgradestatus shows me "0" objects need upgrade.


Friday, October 28, 2011

PowerShell: Add-SPSolution -force when wsp is already deployed

[What you have]:
A 2010 SharePoint Farm. A WSP file that you want to deploy. 

[What you want]:
You want to make sure that a wsp file will be deployed even the solution is already installed.

[What you want to know]: 
To add a solution to the farm - make use of Add-SPSolution. Notice that the Add-SPSolution cmdlet returns the SPSolution object. That means that you can pipe the result  - an added wsp - into Install-SPSolution
-LiteralPath - must be the full path.  You can make use of Resolve-Path to get a a full path from a relative

$path= Resolve-Path .\custom.wsp
$wsp = Add-SPSolution -LiteralPath $path

-local attribute in Install-SPSolution means that the wsp file will be deployed only on the server where the command gets run. That means if farm has more than one web front, all others will not get files installed on their SharePoint root. (what is the SharePoint - read on Best Practices 2010)

-GACDeployment . If wsp has a dll to put into GAC, but the parameter is no specified, an error will be returned. The same true for CASPolicies.

Remember that should do only one deployment at a time. The same true for re-traction.
To check the status of the deployment - use $wsp.Deployed property.

Uninstall-SPSolution will retract a wsp file. Remember to deactivate features first if you are not planing to deploy the wsp or a new version doesn't contain those features. Otherwise, you will leave those features in an invalid state.

Remove-SPSolution to delete the wsp file from the farm. The Farm solution must have been fully retracted before deletion.

Upgrade-SPSolution - will upgrade a solution. This is an alternative for retracting and uninstalling a wsp file before adding and installing a new version. Be mindful that Upgrade-SPSolution works only if you haven't  added a new feature\module to your solution. 


Do you want to know whether wsp will trigger IIS reset? Look at a attribute ResetWebServer in the Solution tag in the manifest.xml

[What you want to do]:
Run the following PowerShell script to deploy a wsp when the wsp is already deployed on the farm: PowerShell Script for SP2010: Add-SPSolution -force when wsp is already deployed

A quick note:
start-sleep ,in my case, helped me to avoid an error:
The solution cannot be removed when a job is scheduled or running

I haven't investigated the true nature of the error and its meaning.
The line Uninstall-SPSolution $wsp -AllWebApplications   -Confirm:$false generates an error:
Cannot uninstall the LanguagePack 0 because it is not deployed.
But still the code executes normally and adds the solution. Again, I haven't investigated the cause of the error. I appreciate your comments\feedback on that matter.

[What you want to consider]:
To get more skilled with PowerShell in SharePoint 2010 - highly recommend to read a book from Gary Lapointe.
Buy the book to support my effort in sharing the experience  through amazon associates:
Automating SharePoint 2010 with Windows PowerShell 2.0




Friday, October 21, 2011

BDCM: How to set permissions through the code?

[What you have]:
You have a BDCM file.


[What you want]:
You want to set permissions on the model and External Content Types (ECT) through the code.


[What you want to know]: 
You need to make sure that you have at least one access control entity with enough permission to avoid an error:
 At least one user/group in the Access Control List must have the SetPermissions right to avoid creating a non-manageable object.

There are 3 options how you can populate permissions through the code.

[What you want to do]:


1. PowerShell:


 $userAccountAdministrator = "{Domain}\{AdminUser}"; 
 $allUsers = "NT AUTHORITY\Authenticated Users";

 $userAdministrator=[Microsoft.SharePoint.BusinessData.Infrastructure.BdcAccessControlList]::TranslateFriendlyStringToEncodedClaim($userAccountAdministrator);
 $allUsers=[Microsoft.SharePoint.BusinessData.Infrastructure.BdcAccessControlList]::TranslateFriendlyStringToEncodedClaim($allUsers);

 $bdcRightsAdministrator= @([Microsoft.BusinessData.Infrastructure.BdcRights]::Execute, [Microsoft.BusinessData.Infrastructure.BdcRights]::Edit,[Microsoft.BusinessData.Infrastructure.BdcRights]::SetPermissions,[Microsoft.BusinessData.Infrastructure.BdcRights]::UseInBusinessDataInLists,[Microsoft.BusinessData.Infrastructure.BdcRights]::SelectableInClients); 
 $bdcRightsAllUsers= [Microsoft.BusinessData.Infrastructure.BdcRights]::Execute; 


 $aceAdministrator = New-Object "Microsoft.SharePoint.BusinessData.Infrastructure.IndividualAccessControlEntry" -arg $userAdministrator,$bdcRightsAdministrator ;
 $aceAllUsers=New-Object "Microsoft.SharePoint.BusinessData.Infrastructure.IndividualAccessControlEntry" -arg $allUsers,$bdcRightsAllUsers ;

$models=@(
"{Your model1}",
"{Your model2}",
"{Your model3}"
);


foreach ($modelName in $models)
{
$Model = Get-SPBusinessDataCatalogMetadataObject -BdcObjectType "Model" -name $modelName -ServiceContext {web app url}


$lbsAcl=$Model.GetAccessControlList();                                                                                                                                                                                                                           
$lbsAcl.Add($aceAdministrator);                                                                                                                                                                                                                                                        
$Model.SetAccessControlList($lbsAcl);                                                                                                                                                                                                                           


$entities=$Model.AllEntities;


foreach ($entity in $entities)
    {
      Write-Host $entity.DefaultDisplayName 


      $acl= $entity.GetAccessControlList(); 
      $acl.Add($aceAdministrator);
      $acl.Add($aceAllUsers);                                                                                                                                                                                                                                                           
      $entity.SetAccessControlList($acl);                                                                                                                                                                                                                                         
      $entity.CopyAclAcrossChildren();                                                                                                                                                                                                                                               
    }
}




2.  Feature receiver
Code Snippet: Add an Access Control Entry to a MetadataObject Using the Administration Object Model
  You can copy paste the code into your custom feature receiver.

3. Declaratively in a BDC Model:

  <AccessControlList>
    <AccessControlEntry Principal="{domain}\{AdminUser}">
      <Right BdcRight="Edit" />
      <Right BdcRight="Execute" />
      <Right BdcRight="SetPermissions" />
      <Right BdcRight="SelectableInClients" />
    </AccessControlEntry>
  </AccessControlList>


The BDC Model has a element <AccessControlList> in several places:
1. Permissions on the Model: inside <Model> tag
2. Permissions on External Content Type: inside <Entity> tag
3. Permissions on the method of ECT (in UI if the options is selected "Propagate permissions to all methods of this external content type. Doing so will overwrite existing permissions"): inside <Method> and <MethodInstance>


Thursday, August 11, 2011

SharePoint 2010: PowerShell and Stsadm

[What you have]:
SharePoint 2010 or SharePoint 2007 and desire to start using PowerShell

[What you want]:
You want to understand why you better off  STSADM? And you want small guidelines with PowerShell.

[What you want to know]:

 "STSADM has been officially deprecated by Microsoft and may not appear in the future version of SharePoint (after 2010). So it's a good idea to start reducing or eliminating your dependency on STSADM"
 (Automating SharePoint 2010 with Windows PowerShell 2.0)

The reason I have shifted to PowerShell one year ago while still working with  SharePoint 2007 was an emergency. We systematically abused SharePoint 2007 by changing schema of already existed list. At the some point on Prod we had the biggest list broken. The only way to fix it without restoring backup and keeping the desired schema changes is to use PowerShell! I have fixed the list in an hour on live Prod and reapplied changes directly on the list through SharePoint API. All of this was done in one tiny Powershell window. Feel grateful and felt in love with PowerShell forever...

What is PowerShell anyway? It's a scripting language.  And also it's an environment where the script is executing. It's quite easy to write a powerful command with some additional looping and filtering. You can build the same logic as using C#. In fact, PowerShell's capabilities are fully featured and mirror the capabilities of C# language, with only slight differences in syntax.

The source of well-known and stable scripts for 2007 SharePoint:
PowerShell:
http://sharepointpsscripts.codeplex.com/
STSADM:
http://blog.falchionconsulting.com/index.php/downloads/

Here is a great resource to borrow a PowerShell script for a particular need: http://gallery.technet.microsoft.com/scriptcenter .

Index of SharePoint Server 2010 Windows PowerShell cmdlets

Stsadm to Windows PowerShell mapping (SharePoint Server 2010)

SharePoint 2010 is shipped with PowerShell 2.0.In SharePoint 2010 PSSnapin (Microsoft.SharePoint.PowerShell) there are more than 530 cmdlets ("command-lets"). The great news is you don't need to learn all of them. Start easy.

Here are  few small hints for easy-going start:

  • Get-Help. The best way to learn PowerShell is to use help command.
  • Get-SP<noun> | Get-member . Make a habit to observe available methods and properties first. It help to write more appropriate script
  • -Whatif . Use the risk mitigation parameters. 
Get-Process  | Stop-Process -whatif. The command produces the following example - what would be performed if I executed the command without the -whatif parameter.
  • Set-ExecutionPolicy AllSignedThe AllSigned execution policy is best for production since it forces the requirement for digital signatures on all scripts and configuration files.  (Signing PowerShell Scripts)
  • To prevent memory leak while working with such objects as SPSite, SPWeb, SPSiteAdministration - become familiar with Start-SPAssignment and Stop-SPAssignment. By default PowerShell runs every command in the new thread. Consider for COM objects (such as SPSite, SPweb, SPSiteAdministration) set $Host.Runspace.ThreadOptions ="ReuseThread" (refer for an example to sharepoint.ps1)). Start-SPAssignment and Stop-Assegnment will not work correctly unlesss Reuse Thread is specified.
  • Refer to Stsadm to Windows PowerShell mapping for easy PowerShell adoption
  • In order to run script file (*.ps1) you need to change the default value of Execution Policy OR Sign the script. The best recommendation is not lower the restriction further than "RemoteSigned". But be aware  that ExecutionPolicy is not a security feature. It can be easily overcame.
Best practices:
 On prod create a custom profile $profile.AllUsersAllHosts where specify  :
- $ConfirmPreference="Low"  PowerShell will automatically question all actions to confirm;
Start-Transcript. It will record all Powershell activity 



P.S. SharePoint 2010 Management Shell is a just a PowerShell instance that loads sharepoint.ps1 script. So, you are free to use your own favorite IDE to build scripts, just load sharepoint.ps1 (Simple concept: How to use SharePoint cmdlets in PowerShell ISE)

[What you want to do]:
Are you brand new to PowerShell? To start easy and fast,  go to PowerShell and SharePoint: What, Why and How
Here is series of PowerShell introduction PowerShell Week: Learn It Now Before It's an Emergency