Archive for the ‘ Powershell ’ Category

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 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: