zoukankan      html  css  js  c++  java
  • Powershell在sharepoint2010使用(转)

    Start all enabled timer jobs on a SharePoint 2010 farm using PowerShell and check their status

    Starting a timer job is fairly easy with PowerShell on SharePoint 2010 using the Start-SPTimerJob command, but the script below walks through each timer job in the farm, checks that it is enabled for use (there’s not much point in trying to start a disabled timer job!), and then starts it:

    Get-SPTimerJob | where { $_.IsDisabled -eq $false } | sort $_.Name | ForEach-Object {
    try
    {
    $timerJobName = $_.Name
    if ($_.WebApplication -ne $null) { $waMessage = "on web application $($_.WebApplication.Url)" }
    else { $waMessage = "on Farm" }
    Start-SPTimerJob -Identity $_
    Write-Host "Started timer job $timerJobName $waMessage"
    }
    catch
    {
    Write-Host "There was a problem starting timer job $timerjobName:" $_
    }
    }

    This can be quite useful if you want to run everything in the farm before performing maintenance or as a test to ensure all timer jobs are operating successfully. Note that the script will report whether it is starting the timer job at the farm level or for each web application.

    If you want to look at a report of the current status of each timer job, run the following script:

    function Get-SPTimerJobStatus
    {
    Get-SPTimerJob | sort Name | ForEach-Object {
    $lastRun = $_.HistoryEntries | Select-Object -first 1
    if ($_.WebApplication -eq $null) { $level = "Farm" }
    else { $level = $_.WebApplication.Url }
    $values = @{
    "Name" = $_.Name
    "Level" = $level
    "StartTime" = $lastRun.StartTime
    "EndTime" = $lastRun.EndTime
    "Status" = $lastRun.Status
    }
    New-Object PSObject -Property $values | Select @("Name","Level","StartTime","EndTime","Status")
    }
    }
    Get-SPTimerJobStatus | Out-GridView

    This will produce a grid view showing each timer job, whether it was run at the farm or web application level, and the last run status, as shown in the example screenshot below:

    image

     

    Sending SharePoint system notification e-mails using PowerShell

    The script in this article demonstrates an example of how you could use PowerShell to send system notification e-mails to administrators on a scheduled basis. Of course, there are a number of ways to do this sort of thing, including SharePoint workflows, Microsoft SCOM, and custom code. I’m not saying PowerShell is necessarily better than these methods, but I like the flexibility it brings, and as you have full access to the Object Model, you could send notifications from all sorts of areas – for example, successes and errors from the crawl logs, information from the User Profile service application, timer jobs with last run times, list items, site users, etc.

    The example I have chosen here is to send an HTML e-mail listing the currently active items from the SharePoint Health Analyzer. This information is effectively just stored in a SharePoint list on the Central Administration site, so I will need to access the list, query the active items and send this information using the SMTP mail server and reply addresses specified in the farm outbound e-mail settings.

    HealthAnalyzerScreenshot

    First of all we need to get the Central Administration web application and site objects from the farm. Note that we do not need to specify any URLs here - The command will automatically find Central Administration using options provided in the SharePoint 2010 cmdlets:

    #Get Central Admin Web Application and Web objects
    $caWebApp = (Get-SPWebApplication -IncludeCentralAdministration) | ? { $_.IsAdministrationWebApplication -eq $true }
    $caWeb = Get-SPWeb -Identity $caWebApp.Url

    Next we can specify the user or group e-mail address that will receive the message, followed by the sender’s e-mail address and the name of the SMTP server sending the message, which I am taking from the farm outbound e-mail settings stored in the Central Administration web application. If you want to send the message to more than one user or group, you could set up an array and walk through each item.

    #Set up from, to and server addresses
    $toAddress = "svc_installsp2010@domain2010.lab"
    $fromAddress = $caWebApp.OutboundMailReplyToAddress
    $serverAddress = $caWebApp.OutboundMailServiceInstance.Server.Address

    The following part of the script gets the Health Analyzer list (internal name “HealthReports”) and the default display form URL. We need this URL later when configuring hyperlinks in the HTML, so that users can click on a health report directly from the e-mail to show it in the browser.

    #Get Health Analyzer list on Central Admin site
    $healthList = $caWeb.GetList("\Lists\HealthReports")
    $displayFormUrl = $caWeb.Url + ($healthList.Forms | where { $_.Type -eq "PAGE_DISPLAYFORM" }).ServerRelativeUrl

    This is probably the trickiest part of the script as it uses a CAML query to find all items in the Health Analyzer, except for those with the Severity column set to “4 – Success”. In other words, it queries any item that the Health Analyzer considers to be a problem on the farm. The CAML itself is specified in the first line below – I’m not going to go into how to write this stuff as there are quite a number of references available on the Internet already.

    $queryString = "<Where><Neq><FieldRef Name='HealthReportSeverity' /><Value Type='Text'>4 - Success</Value></Neq></Where>"
    $query = New-Object Microsoft.SharePoint.SPQuery
    $query.Query = $queryString
    $items = $healthList.GetItems($query)

    This next section creates the subject and HTML body for the e-mail message. If you know HTML then you will see what is happening, and if you don’t then that’s another subject for you to learn! The key part from a SharePoint perspective is the foreach ($item in $items) routine, as this is where the script walks through each list item found from the query above and injects the column values into the HTML. Note where the $displayFormUrl variable is used from earlier to set up the URL used for the hyperlink. I’m also using the built-in ConvertTo-Html PowerShell cmdlet to format the HTML.

    #Set up e-mail message subject and HTML body
    $msgTitle = "Health Analyzer results for farm " + $caWebApp.Farm.Name + " - " + (Get-Date)
    #HTML head
    $head = "<style type=`"text/css`">.tableStyle { border: 1px solid #000000; }</style>"
    $head = $head + "<Title>$msgTitle</Title>"
    #Create HTML body by walking through each item and adding it to a table
    $body = "<H2>$msgTitle</H2><table cellspacing=`"0`" class=`"tableStyle`" style=`" 100%`">"
    foreach ($item in $items)
    {
    $itemUrl = $displayFormUrl + "?id=" + $item.ID
    [array]$itemValues = @($item["Severity"], $item["Category"], $item["Explanation"], $item["Modified"])
    $body = $body + "<tr>"
    $body = $body + "<td class=`"tableStyle`"><a href=`"" + $itemUrl + "`">" + $item.Title + "</a></td>"
    $itemValues | ForEach-Object {
    $body = $body + "<td class=`"tableStyle`">$_</td>"
    }
    $body = $body + "</tr>"
    }
    $body = $body + "</table>"
    #Create message body using the ConvertTo-Html PowerShell cmdlet
    $msgBody = ConvertTo-Html -Head $head -Body $body

    Finally, the commands below use the System.Net.Mail .NET class to send the e-mail, using the IsBodyHtml boolean property to ensure it goes as an HTML message.

    #Create e-mail message object using System.Net.Mail class
    $msg = New-Object System.Net.Mail.MailMessage($fromAddress, $toAddress, $msgTitle, $msgBody)
    $msg.IsBodyHtml = $true
    #Send message
    $smtpClient = New-Object System.Net.Mail.SmtpClient($serverAddress)
    $smtpClient.Send($msg)
    $caWeb.Dispose()

    That’s it! The e-mail will be sent when the script is run and should look similar to the one shown below. As you can see, the items in the e-mail match up to the items shown in the Health Analyzer screenshot at the beginning of this article.

    HealthAnalyzerEmail

    Managing, creating and deleting SharePoint list views with PowerShell

    Due to the number of configuration options available, manipulating list views through PowerShell can be quite involved and I certainly wouldn’t recommend it if you only have a few lists to change. However, when there are a large number of views and lists involved, PowerShell can significantly reduce the amount of time needed to manage and configure them.

    Manage List Views

    The first stage is looking at the commands to manage available views on a list. For this example, I am going to get the “Shared Documents” document library from a root site and assign it to a variable called $list:

    $web = Get-SPWeb http://portal
    $list = $web.GetList(($web.ServerRelativeUrl.TrimEnd("/") + "/Shared Documents"))

    To find the title and URL of the current default view, type the following command:

    $list.DefaultView | select Title, Url

    DefaultView

    If you want to show one of the non-default views then you can call it with the display name, as follows:

    $list.Views["Test View"]

    To change the default view for the list, type the following set of commands for the view you want to configure as the new default:

    $view = $list.Views["Test View"]
    $view.DefaultView = $true
    $view.Update()

    Create New List Views

    The easiest way to create a list view using PowerShell is to create one in the UI first with all the settings you need. You can then use the properties of the view you have created to define the parameters required for the view creation script we use later in this section.

    For this example, I have created a new view called “Sort by modified date”, which is effectively the same as the default “All Documents” view but with the items ordered by modified date in descending order. I have also added the “File Size” column to the view and specified a limit of 50 items per page.

    Once this is done, type the following set of commands to display the properties of the new view:

    $web = Get-SPWeb http://portal
    $list = $web.GetList(($web.ServerRelativeUrl.TrimEnd("/") + "/Shared Documents"))
    $newview = $list.Views["Sort by modified date"]
    $newview

    ViewPropertiesAndValues

    You should now see a long list of property names and associated values for this view, including Title, Query, RowLimit and ViewFields (i.e., columns). You can also take a look at the value of any one of these properties individually by typing $newview.PropertyName and hitting Enter. For example, to get a full list of ViewFields, type $newview.ViewFields.

    When creating the view in PowerShell, you will need to use some of these properties as mandatory parameters in the script. These mandatory properties are listed below:

    Property Name
    Description
    How it looks in the UI

    Title
    Display name of the view in the UI
    image

    ViewFields
    The columns you wish to show in the view
    image

    Query
    The CAML query used to sort and filter list items in the view
    image

    RowLimit
    The number of items shown per page
    image

    Paged
    Used with the RowLimit to either display the number of items in batches ($true) or limit the number of items shown in total ($false)
    image

    DefaultView
    The default view for the list being configured ($true or $false)
    image

    You can now start writing the script to create the view in another list. The example below creates the view with the parameters shown in the UI examples above into the Shared Documents library on the site http://portal/sites/testsite. The values were simply copied from the property list displayed using the script earlier in this section:

    #Get destination site and list
    $web = Get-SPWeb "http://portal/sites/testsite"
    $list = $web.GetList(($web.ServerRelativeUrl.TrimEnd("/") + "/Shared Documents"))

    $viewTitle = "Sort by modified date" #Title property
    #Add the column names from the ViewField property to a string collection
    $viewFields = New-Object System.Collections.Specialized.StringCollection
    $viewFields.Add("DocIcon") > $null
    $viewFields.Add("LinkFilename") > $null
    $viewFields.Add("Modified") > $null
    $viewFields.Add("Editor") > $null
    $viewFields.Add("FileSizeDisplay") > $null
    #Query property
    $viewQuery = "<OrderBy><FieldRef Name='Modified' Ascending='FALSE'/></OrderBy>"
    #RowLimit property
    $viewRowLimit = 50
    #Paged property
    $viewPaged = $true
    #DefaultView property
    $viewDefaultView = $false

    #Create the view in the destination list
    $newview = $list.Views.Add($viewTitle, $viewFields, $viewQuery, $viewRowLimit, $viewPaged, $viewDefaultView)
    Write-Host ("View '" + $newview.Title + "' created in list '" + $list.Title + "' on site " + $web.Url)
    $web.Dispose()

    You may have a requirement to add this list view to the “Shared Documents” library on every site in a site collection. To do this, we need to wrap the Add method in a ForEach-Object condition for every site in a specified site collection. This script will also report an issue if the Shared Documents library does not exist on one or more sites:

    #Title property
    $viewTitle = "Sort by modified date"
    #Add the column names from the ViewField property to a string collection
    $viewFields = New-Object System.Collections.Specialized.StringCollection
    $viewFields.Add("DocIcon") > $null
    $viewFields.Add("LinkFilename") > $null
    $viewFields.Add("Modified") > $null
    $viewFields.Add("Editor") > $null
    $viewFields.Add("FileSizeDisplay") > $null
    #Query property
    $viewQuery = "<OrderBy><FieldRef Name='Modified' Ascending='FALSE'/></OrderBy>"
    #RowLimit property
    $viewRowLimit = 50
    #Paged property
    $viewPaged = $true
    #DefaultView property
    $viewDefaultView = $false

    #Get the site collection
    Get-SPSite "http://portal/sites/testsite" | Get-SPWeb -Limit All | ForEach-Object {
    $webUrl = $_.Url
    try
    {
    #Get the Shared Documents library
    $list = $_.GetList(($_.ServerRelativeUrl.TrimEnd("/") + "/Shared Documents"))
    #Create the view in the destination list
    $newview = $list.Views.Add($viewTitle, $viewFields, $viewQuery, $viewRowLimit, $viewPaged, $viewDefaultView)
    Write-Host ("View '" + $newview.Title + "' created in list '" + $list.Title + "' on site " + $webUrl)
    }
    catch
    {
    Write-Host ("There was a problem trying to create the view in the site " + $webUrl + ": " + $_)
    }
    }

    By the way, if you create a new view with the same title as one that already exists on a list, it will create an extra view in that list with the same title – not overwrite the previous one.

    Modify Existing List Views

    The scripts above create list views with a limited set of mandatory properties, but there are probably some extra properties that you will also want to set on views. As mentioned earlier, to help you decide which settings you need to configure on a view using PowerShell, create a view in the UI first and list its properties and values by running this script:

    $web = Get-SPWeb http://portal
    $list = $web.GetList(($web.ServerRelativeUrl.TrimEnd("/") + "/Shared Documents"))
    $newview = $list.Views["Sort by modified date"]
    $newview

    For a full description of the properties and methods available for configuring views, please see this article on MSDN. Once you have decided which properties you wish to set, look up the values of the view you created in the UI and use this script to modify a view’s settings using PowerShell. In this example, we will be changing the “Sort by modified date” view configured on the Shared Documents library in site http://portal/sites/testsite so that it can be accessed as a mobile view and is set as the default mobile view for the list:

    #Get the site and list
    $web = Get-SPWeb "http://portal/sites/testsite"
    $list = $web.GetList(($web.ServerRelativeUrl.TrimEnd("/") + "/Shared Documents"))
    #Get the list view to be changed
    $newview = $list.Views["Sort by modified date"]
    #Set the mobile and default mobile view properties
    $newview.MobileView = $true
    $newview.MobileDefaultView = $true
    #Update the view configuration
    $newview.Update()
    $web.Dispose()

    Delete List Views

    Finally, here is a script to delete a list view. The obvious thing to mention here is being careful not to delete the default view on a list, or if you want to, ensure that you change the default view to another one first before doing so. The name of the view we are going to delete in this example is “Sort by modified date” in the Shared Documents library on site http://portal/sites/testsite:

    #Get the site and list
    $web = Get-SPWeb "http://portal/sites/testsite"
    $list = $web.GetList(($web.ServerRelativeUrl.TrimEnd("/") + "/Shared Documents"))
    #Get the list view to be changed
    $newview = $list.Views["Sort by modified date"]
    #Delete this view from the list
    $list.Views.Delete($newview.ID)
    $web.Dispose()

    Resetting the SharePoint 2010 search index using PowerShell

    The script here resets the SharePoint 2010 search index, which I have posted as there is no out-of-the-box cmdlet for doing this. This effectively does the same thing as the Index Reset option for the search service application in Central Administration:

    ResetIndex

    Note there are two parameters you can specify in the Reset method:

    • Disable alerts: $true if the Search alerts should be disabled during reset; otherwise, $false. Selecting $true here is the same as ticking the “Deactivate search alerts during reset” checkbox shown in the screenshot above.
    • Ignore unreachable server: $true if the failures to connect to servers are ignored; otherwise, $false.

    In the script example I have added below, both options are set to $false. Note that running this script will permanently delete all crawled data in the search service application – you will need to re-crawl your content sources to get it back.

    #Get the search service application
    #You will need to specify the -Identity switch and a name if you have more than one
    $sa = Get-SPEnterpriseSearchServiceApplication

    #Reset index with the following options in brackets:
    #Disable Alerts $true/$false
    #Ignore unreachable server $true/$false
    try
    {
    Write-Host "Attempting to reset the index...please wait"
    $sa.Reset($false, $false)
    Write-Host "Index successfully reset" -ForegroundColor Blue
    }
    catch
    {
    Write-Host "There was a problem resetting the index:" $_ -ForegroundColor Red
    }

    Perform an IISRESET on multiple servers using PowerShell

    This is quite a quick script, but very useful if you need to restart IIS on multiple servers in one hit. The only pre-requisite is to ensure you have local administrator permissions on each server to perform the IISRESET.

    #Specify servers in an array variable
    [array]$servers = "Server1","Server2","Server3","Server4"
    #Step through each server in the array and perform an IISRESET
    #Also show IIS service status after the reset has completed
    foreach ($server in $servers)
    {
    Write-Host "Restarting IIS on server $server..."
    IISRESET $server /noforce
    Write-Host "IIS status for server $server"
    IISRESET $server /status
    }
    Write-Host IIS has been restarted on all servers

    To use the script, simply replace the server names with those from your SharePoint farm and run on one of the servers.

    The script will also output the status of all IIS related services from each server using the IISRESET /status switch.

    Manage services on SharePoint 2010 servers using PowerShell

    As you may already know, you can use the “Manage Services on Server” option from Central Administration to centrally start and stop service instances across all SharePoint servers in your farm. An example of this administration page is shown below:

    image

    The issue with this page is that it can be cumbersome to use if there are a few servers in your farm and you keep having to click the “Server” drop-down to select one of them. It is also not very repeatable and there may be issues where you might want to automate the process – for example, stopping the User Profile Synchronization Service before a backup or application update and restarting it once complete.

    You can get a similar list to the one shown in Central Admin using PowerShell by typing the following command:

    Get-SPServiceInstance -Server PAC-SP2010 | sort TypeName | Format-Table -AutoSize

    This will not only provide the service name and status, but also the service instance GUID:

    image

    There are a couple of ways to stop a service instance. Firstly, the most user friendly method, which is to use the service display name and then call the Stop-SPServiceInstance cmdlet:

    Get-SPServiceInstance -Server PAC-SP2010 | where-object {$_.TypeName -eq "Managed Metadata Web Service" } | Stop-SPServiceInstance -Confirm:$false

    There are a couple of things to note here:

  • The -Server switch is not required if you are configuring service instances for the server you are currently logged into
  • The -Confirm:$false switch is also optional. Setting this to $false supresses the confirmation prompt that appears when attempting to stop the service instance through PowerShell

    You can also use the Stop-SPServiceInstance cmdlet directly by specifying the service instance GUID, as shown below for the Managed Metadata Web Service on this farm:

    Stop-SPServiceInstance -Identity 3f36d0f4-ce39-48aa-a776-6300f1e2b58f -Confirm:$false

    image

    Restarting the service is simply a case of typing either of the same commands as before, but this time replacing Stop-SPServiceInstance with Start-SPServiceInstance.

    First example:

    Get-SPServiceInstance -Server PAC-SP2010 | where-object {$_.TypeName -eq "Managed Metadata Web Service" } | Start-SPServiceInstance -Confirm:$false

    Second example:

    Start-SPServiceInstance -Identity 3f36d0f4-ce39-48aa-a776-6300f1e2b58f -Confirm:$false

    That’s great, but you also might want to check a service instance has a particular status before attempting to stop or start it. In the example below, the Managed Metadata Web Service instance is associated with the $serviceinstance variable and the Status is checked to make sure it is “Online” before attempting to stop the service instance:

    $serviceinstance = Get-SPServiceInstance -Server PAC-SP2010 | where-object {$_.TypeName -eq "Managed Metadata Web Service" }
    if ($serviceinstance.Status -eq "Online")
    {
    Write-Host "Stopping Managed Metadata Web Service on PAC-SP2010"
    try
    {
    $serviceinstance | Stop-SPServiceInstance -Confirm:$false
    }
    catch { Write-Host "There was an error:" $_ }
    }
    else
    {
    Write-Host "Managed Metadata Web Service on PAC-SP2010 has already been stopped"
    }

查看全文
  • 相关阅读:
    Servlet接口实现类开发步骤
    Servlet概述
    Web服务器之HTTP协议与Tomcat服务器
    vant中van-picker选项插入图片
    排序算法-插入排序
    排序算法-快速排序
    排序算法-冒泡排序
    浅谈C#中Dictionary的实现。
    设计模式(23)-备忘录模式
    设计模式(22)-访问者模式
  • 原文地址:https://www.cnblogs.com/love007/p/2565692.html
  • Copyright © 2011-2022 走看看