Viser opslag med etiketten PowerShell. Vis alle opslag
Viser opslag med etiketten PowerShell. Vis alle opslag

mandag den 16. maj 2016

SharePoint 2013 alignment (1/?)

I have wondering on what I should write next on my blog, and came on a little idea on a serie on how to align two SharePoint 2013 environments.
We are all making new code in an test- or development environment. And for that purpurse we need to establish some valid data in the environments.

So this serie will cover all the steps to create a complete script that can take the production data, and restore it on an test/dev server.

So we should first cover our steps, before we can make a script. And if you have any comments I really like to hear your points. This serie will target those that dont have a deep knowledge in PowerShell and are looking for a copy paste solution.

So the steps are as follow:
  1. Backup (copy style) of the production content database
  2. Check the backup files
  3. Dismount the content databases
  4. Restore the content databases
  5. Assign new site collection admins
  6. Migrate groups and users. (If your changing AD domain)
  7. Migrate service applications
    1. Manage metadata
    2. ... Please ask for a service application, you like me to script. 
So the way I like to make my scripts is making a master script and a funktion script. But it could be the same. I also like to make a configuration file with all my variables.

Lets make 3 files.
  • RunningScript.ps1
  • Functions.ps1
  • Configuration.xml

So lets have a close look at how we build the XML file.
I have build mine with all the server settings.
<?xml version="1.0"?>
<Settings>
<ServerSettings>
 <WebApp>http://contoso.com</WebApp>
<SQLServerFrom>SQLsServer\PRODinstance</SQLServerFrom>
<SQLServerTo>SQLsServer\TESTinstance</SQLServerTo>
<SiteColAdmin>contoso\administrator</SiteColAdmin>
<OldADDomain>ContosoPROD</OldADDomain>
<NewADDomain>ContosoTEST</NewADDomain>
<SQLBackupJob>SQL-Backup-JOB</SQLBackupJob>
<SQLRestoreJob>SQL-Restore-JOB</SQLRestoreJob>
</ServerSettings>

So the first step is to take the backup of the produktion database. This is bedst done by using the SMO PowerShell module.
To install the SMO please look at ...

The first part of the script we need to implement the use of the Functions.ps1 and Configuration.xml file. Note that I am using a "main" function. this is done to get an overview of the running script, and to be able to place it at the top of the script.

Using the RunningScript.ps1
function main
{
  cls
  Write-Host -ForegroundColor Blue "Starting AligmentScript"
  $bits = pwd
  . "$bits\Functions.ps1"
 
  [xml]$xmlConfiguration = Get-Content "$bits\Configuration.xml"
  Run-SQL-Job "$xmlConfiguration.Settings.ServerSettings.SQLServerFrom" "$xmlConfiguration.Settings.ServerSettings.SQLBackupJob"
{

 After in adding the script path, I include the configuration file.
Note: There are many ways to include your script path, I use the "pwd" command, but this dose not always work.
after including the files, I use the function [Run-SQL-Job]. This function is used for both backup and restore. Do mind that the account running the script need access to the production server.

The function looks like this:
function Run-SQL-Job
(
  $instancename,
  $jobname
)
{
 
$db = "MSDB"
   try
   {
 
   $sqlConnection = new-object System.Data.SqlClient.SqlConnection
     $sqlConnection.ConnectionString = 'server=' + $instancename + ';integrated security=TRUE;database=' + $db
     $sqlConnection.Open()
 
   Start-Sleep -s 1
     $sqlCommand = new-object System.Data.SqlClient.SqlCommand
     $sqlCommand.CommandTimeout = 120
     $sqlCommand.Connection = $sqlConnection
    
$sqlCommand.CommandText = "EXEC dbo.sp_start_job N'$JobName'"
     Write-Host "Executing Job => $jobname..."
     $result = $sqlCommand.ExecuteNonQuery() 
     $sqlConnection.Close()
   }
 
  catch
   {
 
   Write-Eventlog -Logname 'Application' -Source 'Application' -EventID 19002 -EntryType Error -Message "Start SQL job :$jobname Failed"
  }
 
# Preload Sql server SMO Assemblies
  $null = [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Connect ionInfo")
  $null = [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum ")
  $null = [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
  # Initilize SMO Objects
  $server = New-Object Microsoft.SqlServer.Management.Smo.Server $instancename
  $i = 0
 
while ($i -ne 100)
  {
    $agent = $server.JobServer.Jobs
 
  if($agent){$i = 100}
    else
    {
 
    Start-Sleep -s 1
      $i += 1
    }
  }
 
$Restore = $agent | Where-Object {$_.Name -eq $jobname}
  $Today = Get-Date
  $continue = $true
 
# Get Time Value to Start and Stop
  $ActiveDateTime=[datetime]::Parse((Get-Date -Format 'HH:MM'))
  $StopDateTime=$ActiveDateTime.addminutes(1)
 
$StopTime=$StopDateTime.toString("HH:MM")
  if ($Restore -eq $null)
  {
 
   Write-host "$jobname does not exist on $instancename"
    $continue = $false
  }
 
if ($continue){write-host -ForegroundColor Blue "$jobname Job is Executing. Please Wait.." -NoNewline}
  while ($continue)
{
$Restore.Refresh()
 
# if Job Completed Successfully     
  if ($Restore.CurrentRunStatus.value__ -eq 4 -and $Restore.LastRunDate -gt $Today.AddDays(-1) -and $Restore.LastRunOutcome -eq "Succeeded")
  {
 
   Write-host "$jobname complete."
    $continue = $false
  }
 
# if Job is curently executing     
  elseif ($Restore.CurrentRunStatus.value__ -eq 1)
  {
 
  Write-host -ForegroundColor Blue "." -NoNewline
    start-Sleep -s 5
  }
 
# if Job Suspended    
  elseif ($Restore.CurrentRunStatus.value__ -eq 5)
  {
 
   Write-host "$jobname Job has been suspended."
    $continue = $false
  }
 
# if Job Cancelled     
  elseif ($Restore.CurrentRunStatus.value__ -eq 4 -and $Restore.LastRunOutcome -eq "Cancelled")
  {
 
    Write-host "$jobname Job has been Cancelled"
     $continue = $false
  }
 }
}
 

 

onsdag den 10. april 2013

Disable all Health analyzer rules in SharePoint 2013


As in SharePoint 2010 we also in SharePoint 2013 have a lot of jobs running and analyzing the overall health of our server.  
All those rules are really nice, but in some cases you don’t need them. 
Example: 
  • If you know that you are running with databases over the limit and you are okay with that. 
  • You are running with only one service account, and is okay with that.
  • Your running whit a smaller page file than your physical RAM  (Quit a big file if you have 48Gb)

They all have in common that you as an admin made choices, and as we all know admins never make bad decisions. So instead of mannerly disable rules one at the time, you can just disable all and enable the ones you need.

To disable all rules just run the script below, this will disable all rules. To include the SharePoint SnapIn read this post  

If you like, this can be combined with a xml file so you can disable rules based on this as well. See this post to get inspiration. I would recommend using this if your maintaining a large organisation with a lot of environments.

PowerShell Script:
------------------------------
function main
{
$healthList = [Microsoft.SharePoint.Administration.Health.SPHealthRulesList]::Local.Items
 foreach ($Listitem in $healthList)
 {
  Write-Host -ForegroundColor Green $listitem.Id ": " -NoNewline
  if ($Listitem["HealthRuleCheckEnabled"] -ne $false)
  {
   Write-Host -ForegroundColor Magenta "Disable job"
   $Listitem["HealthRuleCheckEnabled"] = $false
   $Listitem.Update()
  }
  else
  {
   Write-Host -ForegroundColor White Done -BackgroundColor Black
  }
 }
}

Have fun with PowerShell 


torsdag den 28. februar 2013

Error on UserProfileManager and a funny SiteSubscriptionId


So I was struggling a little bit with an old PowerShell script to import pictures to the user profiles on our Intranet. The script was not working and I need to figure out what went wrong.
So the script is well documented on various forums, so that should be no big deal in getting this to work. So I went head first, and in to the pool I went.

So the script looks like this.
$site = Get-SPSite $mySiteUrl
$context = Get-SPServiceContext $site
$profileManager = New-Object Microsoft.Office.Server.UserProfiles.UserProfileManager($context)

So the first part was easy, just getting the “mysite” URL, Next part to get the mysite service context. Now again quit easy. But then I had to get the profile manager. Then some problems came up.
So when trying to get the profile manager I got this error when running the commands manual.

New-Object : Exception calling ".ctor" with "1" argument(s): "Object reference not set to an instance of an object.” At line:1 char:29
+ $profileManager = New-Object <<<< Microsoft.Office.Server.UserProfiles.UserProfileManager($context)
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

So this had to be the problem to my script.
After some quick test I found my context hade a funny SiteSubscriptionId

SiteSubscriptionId
------------------
00000000-0000-0000-0000-000000000000

So I found that the SiteSubscriptionId will always be a blank Guid unless you have multi-tenancy enabled in the environment, so the problem should be found elsewhere.
I my case I found out that the user running the script was net in the administrators group of the service provider, so adding the user running the script to the group fixed the problem.

Go to Central Administration => Application Management => Manage Service Applications 
Highlight the row “User Profile Service Application”

Click the administrators in the ribbon and add the correct user.
Click the Permissions in the ribbon and add the correct user


onsdag den 20. februar 2013

Adding SharePoint PowerShell snapins


Over time I have seen a lot of ways to add the SharePoint snapins. So I decided that I would share my point of view on this.

So a lot of post on the internet is showing various ways to do this, by as the structure fascist I am, I like to keep things organized. So I always put my code in functions.

Why?

Well first it gives you a nice overview of the code, Always put your main code in a main function. This way it’s always on the top of your script. Second. By adding all your code in functions you can call the reuse then over and over again in your script.

It’s also a good idea to let your script tell you where in the process it is. This gives you a nice overview over watt you script is doing

So how do I add the snapin.

function snapin
{
  $spSnapin = Get-PSSnapin | where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}        
  if($spSnapin -eq $null)
  {
    Add-PSSnapin Microsoft.SharePoint.PowerShell
    Write-Host -ForegroundColor "Green" -Object "SharePoint PowerShell Snapin loaded"
  }
  else        
  {  
     Write-Host -ForegroundColor "Gray" -Object "SharePoint PowerShell Snapin already loaded"
  }
}
  
So after adding this function I call this function just before I call the main function. My structure will always look like this.

function
main
function snapin

snapin
main
# end of script