PowerShell: Interact with SharePoint in the fastest way possible

Vision

PowerShell: Interact with SharePoint in the fastest way possible

Written by: Margriet Bruggeman, Nikander Bruggeman.

May 1, 2010

Windows PowerShell is taking the administrative side of the Microsoft world by storm. What it is? An extensible automation engine built on top of the .NET Framework that allows administrators to perform administrative tasks. This is typically done via cmdlets (command lets) which are specialized .NET classes implementing a particular operation. The investments in PowerShell for SharePoint 2010 have been huge: SharePoint 2007 was shipped with 182 different stsadm commands, during the beta cycle, SharePoint 2010 already has a total of 652 PowerShell cmdlets. We're absolutely convinced that everybody who is serious about his work and wants to call himself a good SharePoint administrator needs to be well versed in PowerShell. That's how important we think PowerShell is for IT Pros.

Note. If you want to use PowerShell to interact with SharePoint 2010, you need to have considerable privileges. You need to have db_owner rights for all SharePoint 2010 databases, and need to be a site collection administrator for the site collections you are interacting with.

If you're not an administrator, but a developer, we don't feel that you need to become a wizard in PowerShell before you can call yourself a good developer. However, we do think it's important to have knowledge about this topic, for two main reasons:

  • It may save you tons of time, because there are a lot of scenarios where PowerShell is simply the fastest way to accomplish things. During development, demonstrations of your applications for the customer, or presentations you might be giving to fellow developers, you will come across actions that need to be performed, such as enabling a feature for every site in a site collection, finding out which content databases are associated to a site collection, or exeucting a specific timer job now. You will find that PowerShell is great for stuff like that.
  • If you're shipping a custom application it would be a great asset if you ship it with a set of custom PowerShell cmdlets that can be used to perform custom administrative tasks specifically for your application. This allows administrators to leverage the knowledge they have about PowerShell, and gives them a consistent management experience which will no doubt make them look more favorable at your application.

In this blog post, we will show all sorts of examples that demonstrate what PowerShell can do for you and the basic knowledge you need to have to work it. First of all, if you want to start using PowerShell and interact with SharePoint 2010, you need to fire up the SharePoint 2010 Management Shell. This automatically loads all SharePoint 2010 related PowerShell cmdlets. Since the primary target audience for using these cmdlets are IT Pros, most cmdlets have a "high-level" focus that at the most fine grained level operates on SharePoint site level (SPWeb object level). The next procedure explains how to start the SharePoint 2010 Management Shell.

  1. Click Start > All Programs > Microsoft SharePoint 2010 Products > SharePoint 2010 Management Shell.
  2. This opens the Administrator: SharePoint 2010 Management Shell command prompt, which looks like this:

It's useless trying to memorize all 600+ cmdlets. Instead, you should memorize how to retrieve a list of all available commands:

get-command

A sample of the cmdlets you can find here are shown in the following Figure.

This is still a bit much information to digest, so you can filter it by name:

get-command get-sp*

The first SharePoint cmdlet that we will take a look at is Get-SPFarm (in case you're wondering, names of cmdlets are not case sensitive). If you want to retrieve the current farm, do this:

Get-SPFarm

This returns an SPFarm object. The command prompt displays the name of the configuration database and status indicator that tells that the farm is online. If you want help using this cmdlet, you can do the following:

get-help Get-SPFarm

You can also request help in the form of realistic examples for using the cmdlet. There are lots of cases when this form of help will give you valuable extra information, it's probably our favorite help mode.

get-help Get-SPFarm -examples

As said before, the Get-SPFarm cmdlet returns an SPFarm object. It's extremely useful to find out which properties an object of this type actually has. You can determine that via:

Get-SPFarm | Get-Member

This would be another good place to apply a filter to the property name:

Get-SPFarm | Get-Member p*

PowerShell is used to automate tasks and a command prompt is the main tool you will be working with. Nevertheless, in some cases you may prefer to interact in a more visual way. In that case, you need to install the Windows PowerShell Integrated Scripting Environment feature from Server Manager, as shown in the next procedure.

  1. Start > Administrative Tools > Server Manager. This opens the Server Manager MMC snap-in.
  2. Click the Features node.
  3. Click Add Features. This opens the Add Features Wizard.
  4. Select the Windows PowerShell Integrated Scripting Environment (ISE) checkbox.
  5. Click Next, followed by Install, then Close.

When you are finished doing that, you will be able to take the output of a cmdlet and use the PowerShell pipestream system (using the pipe symbol or "|") to something else. In this case, we will take the output of the Get-SPFarm cmdlet and redirect it to a special gridview:

Get-SPFarm | Out-GridView -Title "Test"

In the next Figure, we show an example that's just a bit more complex than the previous example, so you get a better idea of what the tool can do for you.

You can redirect ouput results to a wide range of other destinations, such as a CSV file, to name but one:

Get-SPFarm | Export-Csv c:\temp\output.txt

One of the great advantages of PowerShell is that you can store output results in a variable for later use. In the next example, we will store the output of the Get-SPFarm cmdlet in a variable called $Farm:

$Farm = Get-SPFarm

You can take this variable, and use a pipe to determine the properties of the variable:

$Farm | select *

You can also store the call to the Get-SPFarm cmdlet itself in a variable, in which case the variable is called a script block. Then, at a later time, you can choose to execute the script block via Invoke-Command:

$scriptBlock = { Get-SPFarm }
Invoke-Command $scriptBlock

Let's move on to the next SharePoint cmdlet; if you want to look at information about all databases in the entire SharePoint farm you should do this:

Get-SPDatabase

Use the next cmdlet to retrieve all service applications in your SharePoint farm:

Get-SPServiceApplication

The following returns a list of all current web applications:

Get-SPWebApplication

This list doesn't include the web application hosting SharePoint Central Administration. If you want to have that information too, you need to pass an extra parameter:

Get-SPWebApplication -IncludeCentralAdministration

If you don't want to have a list of all web applications, but only a list containing the first five, you can do this:

Get-SPWebApplication | select -First 5

You can sort the output, based on properties such as the display name:

Get-SPWebApplication | Sort DisplayName

Or simply reverse the display name sort order:

Get-SPWebApplication | Sort DisplayName -descending

You can get at a single web application using an indexer:

$webapps = Get-SPWebApplication
$webapps[0]

Or apply more advanced filters:

Get-SPWebApplication | Where { $_.DisplayName -eq "SharePoint 80" }

You can use pipes to perform operations on a result set as well. In this case, we will display all content databases for all web applications by passing in the output containing all web applications to another cmdlet:

Get-SPWebApplication | Get-SPContentDatabase

Again, you can use pipes to find out what you can do with content databases:

Get-SPWebApplication | Get-SPContentDatabase | select *

You could also use an indexer and access a property of one of the content databases in the result set:

$cdb = Get-SPWebApplication | Get-SPContentDatabase
$cdb[0].SqlConnectionString

It requires a special syntax if you want to accomplish something similar to the previous example in one go. The @{Expression=} syntax allows you to specify in which property of a complex object you are interested in. We will also use the special $_ variable that refers to the current instance of an object in a collection. In the next example, we show you how to retrieve the connection string for every content database:

Get-SPWebApplication | Get-SPContentDatabase |
Select Name, @{Expression={$_.SqlConnectionString}}

If you want to retrieve all site collections, simply go:

Get-SPSite

If you want to retrieve a limited amount of site collections:

Get-SPSite -limit 2

You can also retrieve site collections using regular expressions:

Get-SPSite "http://sharepoint2010/(my|)" - RegEx

This returns our default site collection at http://sharepoint2010 as well as the site collection containing personal sites located at http://sharepoint2010/my.

You can apply a whatif construct to commands, which allows you to perform a dry run without actually affecting anything. For instance, the next command shows which site collections would be deleted if you would try to remove all SharePoint 2010 site collections, but it doesn't actually do it:

Get-SPSite | Remove-SPSite -whatif

If you want to loop through each item in a collection, you will need to use the special ForEach-Object construct. The following command displays a property of a sub object of each item in the result set:

Get-SPSite | ForEach-Object { $_.RootWeb.Title}

The next example gets all features for all site collections and applies a sorting based on the display names of the features:

Get-SPSite |% { Get-SPFeature -site $_ } | sort DisplayName

You can take this to the next level by getting all features for all sites within all site collections and sort it by their display name:

Get-SPSite | ForEach-Object { Get-SPFeature -Web $_.Url } | sort DisplayName

The following performs a dry run of enabling the Ratings feature for all sites within all site collections (remove the -whatif part if you actually want to do it):

Get-SPSite | ForEach-Object { Enable-SPFeature "Ratings" -url $_.url -whatif }

If you want to perform a dry run of diasling the Ratings feature for all sites within all site site collections (remove the -whatif part if you actually want to do it):

Get-SPSite | ForEach-Object { Disable-SPFeature "Ratings" -url $_.url -whatif }

The next command retrieves the titles of all sites of a given site collection:

Get-SPSite "http://sharepoint2010" | get-spweb -Limit All | Select Title

You can retrieve all sites and filter the results based on the template of a site:

Get-SPSite "http://sharepoint2010" |
get-spweb -Limit All -Filter {$_.Template -eq "ENTERWIKI#0"} |
Select Title

Alternatively, you can apply a like filter:

Get-SPSite "http://sharepoint2010" | get-spweb -Limit All -Filter {$_.Template -like "E*"} |
Select Title

If you want to know which site templates are available, do:

Get-SPWebTemplate

You can use variables to perform multiple actions, sich as retrieving all lists and list items of a root site of a SharePoint site collection, and still keep to code clean and easy to read by using multiple variables:

$site = Get-SPSite "http://sharepoint2010"
$root = $site.RootWeb
$root | GetMember (if you're not sure what it's members are)
$lists = $root.lists
$lists | ForEach-Object { $_.Title }
$pagesList = $lists["Pages"]
$items = $pagesList.Items
$items | ForEach-Object { $_.Title }

PowerShell can be used locally on the server, but you can use it to issue remote commands to (with the help of the Invoke-Command cmdlet), which is really handy if you want to retrieve information about another server in your SharePoint farm. If you want to do this, you first need to enable PowerShell remoting (by starting WinRM on each server). You can do this via the following command (just accept all options presented to you):

Enable-PSRemoting

When accessing other servers, you typically will want to have a change to provide credentials without having to hard-code them. You can do this by calling the Get-Credential cmdlet which causes the Windows PowerShell Credential Request dialog window to open. This dialog window allows you to specify a user name and a password. The cool thing is, you can assign the result to a variable and use it later when making a remote call. The next Figure shows the Windows PowerShell Credential Request dialog window.

The next command shows how to read the contents of a web.config file on a remote machine (remember: that machine needs to have WinRM enabled) and passes credentials as a part of the call:

$cred = Get-Credential
Invoke-Command -ComputerName sharepoint2010 -ScriptBlock {Get-Content
c:\inetpub\wwwroot\wss\VirtualDirectories\80\web.config} -Credential $cred

Even greater, you can run a remote command on multiple computers at the same time:

Invoke-Command -ComputerName WFE1, WFE2 -ScriptBlock {Get-Content
c:\inetpub\wwwroot\wss\VirutalDirectories\80\web.config} -Credential $cred

We're concluding this section with examples related to something that we have needed a zillion times in the past and is made real easy in PowerShell. First, we're retrieving a list of all timer jobs:

Get-SPTimerJob

Finally, we use the information found via the Get-SpTimerJob to execute a single timer job, using the following syntax:

Get-SPTimerJob [name of timer job]

In the previous example of the blog post, we're executing a timer job called job-workflow, and we're executing it now:

Get-SPTimerJob job-workflow | Start-SPTimerJob

By now, you have seen loads of examples of using PowerShell for SharePoint. We have covered the essentials you need to learn in order to become effective with it and we hope you agree PowerShell for SharePoint is a valuable addition to your bag of tricks.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值