Posts Tagged ‘ Powershell

How to fix broken images after mySite URL change in SharePoint 2010?

Here is a small PowerShell script to fix the pictureurl for all userprofiles after changing the mySite Url:

$mySiteWebapplicationUrl = "https://mysite.normanbauer.com/"
#current Url of your mySite website

$mySiteOldUrlValue = "http://mysitetest:80/"
#former Url where your pictures do not reside any more

$mySiteNewUrlValue = "https://mysite.normanbauer.com:443/"
#current Url where your images can be found now

$mySite = Get-SPSite $mySiteWebapplicationUrl
$SPServiceContext = Get-SPServiceContext $mySite
$userProfileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($SPServiceContext)
$userProfiles = $userProfileManager.GetEnumerator()

foreach ($userProfile in $userProfiles)
{
  #if pictureurl is not empty replace the old url part with the new one
  if ($userProfile["PictureURL"] -ne '')
  {
    $oldPictureUrl = $userProfile["PictureURL"].toString()
    $newPictureUrl = $oldPictureUrl.Replace($mySiteOldUrlValue, $mySiteNewUrlValue)
    write-host "oldPictureUrl = " $oldPictureUrl " --> newPictureUrl = " $newPictureUrl
    $userProfile["PictureURL"].Value = $newPictureUrl
    $userProfile.Commit()
  }
}

How to get detailed information on Windows boot and shutdown performance in PowerShell?

In Windows 7 administrators have the possibility to monitor boot and shutdown performance by reviewing event logs. The most common one is located at Event Viewer > Application and Services Logs > Microsoft > Windows > Diagnostics-Performance > Operational. Events with an ID of 100 for boot up and 200 for shutdown will give you some basic information on the general tab, for example, when did the last boot up or shutdown happen and how long took it to complete and more detailed information on the Details tab.

On the Details tab you can find even more. Here is how to get this information programatically with the help of powershell. Run the following commands from an elevated powershell:

$bootevents = Get-WinEvent -FilterHashtable @{logname="Microsoft-Windows-Diagnostics-Performance/Operational"; id=100}
$bootevent = [xml]$bootevents[0].ToXml()
$bootevent.Event.EventData.Data

$shutdownevents = Get-WinEvent -FilterHashtable @{logname="Microsoft-Windows-Diagnostics-Performance/Operational"; id=200}
$shutdownevent = [xml]$shutdownevents[0].ToXml()
$shutdownevent.Event.EventData.Data

These upper 3 lines will get all events from the named logfile with the event id 100. Afterwards in converts the first result to xml, which now can be used in different ways. At this time we just want to print it on the screen. The lower 3 lines will do the same for shutdown events with event id 200.

This is the boot result for my computer:

Name                                    #text
----                                    -----
BootTsVersion                           2
BootStartTime                           2012-01-10T07:33:36.656000300Z
BootEndTime                             2012-01-10T07:35:43.438676400Z
SystemBootInstance                      167
UserBootInstance                        122
BootTime                                78563
MainPathBootTime                        30263
BootKernelInitTime                      28
BootDriverInitTime                      1521
BootDevicesInitTime                     1809
BootPrefetchInitTime                    0
BootPrefetchBytes                       0
BootAutoChkTime                         0
BootSmssInitTime                        7424
BootCriticalServicesInitTime            534
BootUserProfileProcessingTime           4625
BootMachineProfileProcessingTime        10802
BootExplorerInitTime                    2383
BootNumStartupApps                      17
BootPostBootTime                        48300
BootIsRebootAfterInstall                false
BootRootCauseStepImprovementBits        0
BootRootCauseGradualImprovementBits     0
BootRootCauseStepDegradationBits        0
BootRootCauseGradualDegradationBits     0
BootIsDegradation                       false
BootIsStepDegradation                   false
BootIsGradualDegradation                false
BootImprovementDelta                    0
BootDegradationDelta                    0
BootIsRootCauseIdentified               false
OSLoaderDuration                        1026
BootPNPInitStartTimeMS                  28
BootPNPInitDuration                     1990
OtherKernelInitDuration                 1006
SystemPNPInitStartTimeMS                2990
SystemPNPInitDuration                   1340
SessionInitStartTimeMS                  4337
Session0InitDuration                    5181
Session1InitDuration                    1192
SessionInitOtherDuration                1050
WinLogonStartTimeMS                     11761
OtherLogonInitActivityDuration          691
UserLogonWaitDuration                   8463

And here is the shutdown result:

Name                                    #text
----                                    -----
ShutdownTsVersion                       1
ShutdownStartTime                       2012-01-07T15:06:38.501239300Z
ShutdownEndTime                         2012-01-07T15:07:03.559344800Z
ShutdownTime                            25058
ShutdownUserSessionTime                 2728
ShutdownUserPolicyTime                  37
ShutdownUserProfilesTime                84
ShutdownSystemSessionsTime              20852
ShutdownPreShutdownNotificationsTime    15732
ShutdownServicesTime                    5007
ShutdownKernelTime                      1477
ShutdownRootCauseStepImprovementBits    0
ShutdownRootCauseGradualImprovementBits 0
ShutdownRootCauseStepDegradationBits    0
ShutdownRootCauseGradualDegradationBits 0
ShutdownIsDegradation                   false
ShutdownTimeChange                      0

Have a look at this blog post to learn how to push this data into a SQL database with powershell.

How to configure item level recovery for Sharepoint 2010 with DPM 2010

I know that there are already a couple of articles covering this issue – but since I ran into trouble with exactly this configuration issue I realized that these articles do not cover everything. For example the problems you can run into.

To keep the steps to be taken as simple as possible I explain it regarding a Sharepoint farm with one server called “SHAREPOINT1″ and a DPM server called “DPM1″. The database server is sharepoint2010_test_db but we will not need this one while configuring backup.
Even in larger farms the steps to be taken will remain the same, because you will need to configure just one web frontend server.

First we need to deploy the Data Protection Manager 2010 agent. Just do it like you always did before:

  1. Open the DPM 2010 Administrator Console
  2. Switch to the management tab
  3. On the Agents panel hit “Install…”
  4. In the “Protection Agent Installation Wizard” choose “Install agents”
  5. Add your Sharepoint web frontend server
  6. Hit Next and enter you credentials
  7. Click Next and choose to not automatically restart the server
  8. On the last page click Install

When the installation is complete log on to your Sharepoint 2010 server and open an elevated command prompt. Now you need a domain account that has the farm administrator right and local administrator right on the server. I used the database access / farm administrator account used when deploying the farm: normanbauer.com\sp2010_test_fa. Of course you will also need its password!

Now type the following in the elevated command prompt (line by line; you may need to change the directory):

cd "%programfiles%\Microsoft Data Protection Manager\DPM\bin"
ConfigureSharepoint.exe -EnableSharePointProtection
ConfigureSharepoint.exe -EnableSPSearchProtection

For each of the ConfigureSharepoint commands you’ll need the account mentioned before. If the account you are using is not a member of the local administrators group on the server you will get an error message like this: “The specified Username and Password combination is Invalid.”

If everything worked correctly both commands will return “Operation completed successfully.” :

The account used for those two commands will be used as the run as credentials of a DPM developed DCOM object called WssCmdletWrapper:

Now you can configure the Sharepoint 2010 protection group in DPM. Again, go to the DPM 2010 Administrator Console and open the “Protection” panel. Create a new or modify an existing protection group. Add the server by choosing the database child item below the Sharepoint node of your server.

After completing the wizard DPM will start to synchronize all data. After that, you can review the progress in the Monitoring > Jobs panel, your databases can be restored using the Recovery panel. Simply navigate to your server > All Protected SharePoint Data > your database name. In the Recoverable Items list you can see your AdminContent DB, Config DB and any other Application databases you created before.

The problem now is, that you cannot navigate your application databases down to single items. DPM needs to create a catalog containing all urls of your Sharepoint sites first. This operation can take up to 24 hours but you can force DPM to do so immediately using PowerShell.

Open the DPM Management Shell from start menu and enter the following commands (please modify them to meet your servers names):

$dpmserver = "DPM1"
$sharepointserver = "SHAREPOINT1"
$pg = Get-ProtectionGroup $dpmserver
$ds = $pg | Get-Datasource
$sp = $ds | Where-Object {"$_.computer" -like "*" + $sharepointserver + "*" -and $_.type -like "*SharePoint*"}
$sp | Start-CreateCatalog

or as a one-liner:

Get-ProtectionGroup DPM1 | Get-Datasource | Where-Object {"$_.computer" -like "*SHAREPOINT1*" -and $_.type -like "*SharePoint*"} | Start-CreateCatalog

Now you should be able to navigate down to every single item of your farm:

If this is still not possible your account used to enable Sharepoint protection may not have sufficient rights. I had the problem when I first used a separate backup account that did not have a certain permission – I still do not know which one. I am currently using the farm administrator account, which is not a perfect solution but it works.

There is only one problem I found using that account: You cannot let Sharepoint change its password automatically from the managed accounts. Doing so would result in backup not working properly because the DCOM object mentioned before would need to be configured to use always the current password, which is not possible (as far as I know).

How to use environment variables in Powershell?

Sometimes you need to use an environment variable (eg. username, userprofile, computername, …) in Powershell.

The location where environment variables are stored is “env:”. This behaves similar to a hard or flash drive. You can list its content or browse it by using

dir env:

The output shows all existing environment variables you can use. But how to use them?

You can get every environment variable by using the get-content or for short gc cmdlet.

$computername = get-content env:computername
$username = gc env:username

List of environment variables in Windows 7 / XP

How to read and use the contents of a website from Powershell?

First we need to create a xmlhttp object, similar to what you would do in JavaScript

$objXmlHttp = New-Object -ComObject MSXML2.ServerXMLHTTP

Use the open method to specify the url, optional username and password. The third parameter (optional) is a boolean indicator of whether the call is asynchronous – the default is true.

$objXmlHttp.Open("GET", "http://www.normanbauer.com", $False, "username", "password")
$objXmlHttp.Send()

Now we can work with the results

$content = $objXmlHttp.responseText
$status = $objXmlHttp.status
$statustext =$objXmlHttp.statusText

How to connect to / read from / write to SQL Server from Powershell?

First create the connection object, set the connection string and open the connection:

$objSqlConnection = New-Object System.Data.SqlClient.SqlConnection
$objSqlConnection.ConnectionString = "Server=YourSqlServer; Database=YourDataBase; User Id=YourUsername; password=YourPassword"
$objSqlConnection.Open()

You can also use “Integrated Security=true;” instead of “User Id” and “password” to login with the user executing the script.
Now create a SqlCommand, set its query and execute it:

$objSqlCommand = $objSqlConnection.CreateCommand()
$objSqlCommand.CommandText = "INSERT INTO northwind.dbo.testtable (YourColumnName) VALUES (YourColumnData)"
$objSqlCommand.ExecuteNonQuery()

This will execute inserts and updates, commands that will not return any data. To query your tables you can use following code.

Create a reader, set a query again, execute it and read its results:

$objSqlCommand.CommandText = "SELECT column_str, column_int, column_flt,  FROM northwind.dbo.testtable"
$objSqlReader = $objSqlCommand.ExecuteReader()
while($objSqlReader.Read())
{
  $column_str = $objSqlReader.GetString(0)
  $column_int = $objSqlReader.GetInt32(1)
  $column_flt = $objSqlReader.GetFloat(2)
}

Finally close the sql connection.

$objSqlConnection.Close()

Documentation for functions, methods and properties used in this post: