Create tool for Visual Studio 2010 to extract the full qualified public assemby name with PowerShell

I created a simple tool extension for Visual Studio for extracting the full qualified name of an .NET assembly.

Like this: http://msdn.microsoft.com/en-us/library/ee539398.aspx but without a compiled application.

I used PowerShell for this.

HERE ARE THE STEPS:

    1. Got to Visual Studio 2010
    2. Open Menu “Tools”
    3. Open Dialog “External Tools”
    4. Click “Add” to add a new tool entry
    5. Specify “Full Assembly Name” as “Title”
    6. Enter “c:windowssystem32WindowsPowerShellv1.0powershell.exe” as “Command”
    7. Enter
      -command "&{[System.Reflection.AssemblyName]::GetAssemblyName('$(TargetPath)').FullName}"

      as “Arguments”

    8. Check “Use output window”
    9. Click “OK”
    10. You can use this tool if your output binary can be compiled(!)

Screenshots:

image

image

Error while enabling Session State Service on SharePoint 2010

There are some mysterios errors on my SharePoint farm. After reading tons of log files I found some hints to problems with the “Session State Service” of SharePoint 2010.

I found this Cmdlets in PowerShell for controlling this service:

Enable-SPSessionStateService 
Disable-SPSessionStateService
Get-SPSessionStateService
Set-SPSessionStateService

I tried to enable the service with the first Cmdlet. – This was the resulting error:

image

Error message: “Microsoft SharePoint Server session state could not find the Session State Service. Contact your farm administrator.”

There is no information about this error in the internet. (Till now Smile )

MY SOLUTION FOR MY PROBLEM (may be it does not help you in your special situation. It’s “experimental”!!!):

I created a PowerShell script for re-creating the Session State Service and its Service Application.

Before you go on: Make sure, the Windows service “ASP.NET State Service” is running. (I set it to start automatically during system startup.)

This is the resulting script:

#region Check x64 host
    if( [System.IntPtr]::Size -ne 8) {
      Write-Error "Please use a x64 PowerShell host!"
      return
    }
#endregion

#region Load SharePoint SnapIn and DLL
  Remove-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
  Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
  
  #Check available SharePoint Cmdlets
  if( (Get-Command -Noun SPWeb*) -eq $null ) {
    Write-Error "SharePoint SnapIn not loaded. SharePoint cmdlets missing!"
    return
  }
#endregion

cls

$farm = [Microsoft.SharePoint.Administration.SPFarm]::Local

$services = $farm.get_Services() #get all SharePoint services
$sessionStateService = ($services | ? { $_.TypeName -like "*session state*" } ) #find the existing Session State Service -> it was "NULL" for me!

if( $sessionStateService -eq $null ) {
    #Recreate the Service
    $newSessionStateService = New-Object Microsoft.Office.Server.Administration.SessionStateService ("", $farm)
    $newSessionStateService.Id = [System.Guid]::NewGuid()
    $newSessionStateService.Name=[String]::Empty
    $newSessionStateService.Update()
    $farm.Update()
    $newSessionStateService.Provision()
    $newSessionStateService.Name=[String]::Empty
    $newSessionStateService.Update()
}

$services = $farm.get_Services() 
$sessionStateService = ($services | ? { $_.TypeName -like "*session state*" } ) 

$servers=(Get-SPServer)

#Create service instances on all application servers of the SharePoint farm
$servers | % {
    if( $_.Role -eq "Application" ) {
      $currentSessionStateSvcOnServer = ($_.ServiceInstances | ? { $_.TypeName -like "*session state*" } ) 
      if( $currentSessionStateSvcOnServer -eq $null ) {
        #write-host $_.Name $server.Role $_.gettype().fullname
        
        #To create a service instance you must use a "protected" constructor
        [type]$t = "Microsoft.SharePoint.Administration.SPServiceInstance" -as "Type"
        $p = @( ("string" -as [Type]), ("Microsoft.SharePoint.Administration.SPServer" -as [Type]), 
                ("Microsoft.SharePoint.Administration.SPService" -as [Type]) )
        $c = $t.GetConstructor([System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Instance,$null, $p, $null)
        #these are the parameters for creating a service instance by using the protected constructor
        [Object[]]$params = @([Object]"Session State Service Instance", 
                              [Object]([Microsoft.SharePoint.Administration.SPFarm]::Local.Servers[$_.Name]), 
                              [Object]([Microsoft.SharePoint.Administration.SPFarm]::Local.Services[$sessionStateService.Id]))
        $newSvcInstance = $c.Invoke($params)
        #update & provisioning
        $newSvcInstance.Update()
        $newSvcInstance.Provision()
      }
    }
}

if( (Get-SPSessionStateService -ErrorAction SilentlyContinue) -ne $null ) {
  Write-Host "Successfull :-)" -ForegroundColor Green
} else {
  Write-Host "Failed :-(" -ForegroundColor Red
}

After that, the “Enable-SPSessionStateService” works:

image

(Spend me 1 1/2 days.)


You can use this script to delete the Session State Service, e.g. if some script parts does not work as expected. ONCE MORE: USE IT CAREFULLY AND AT YOUR OWN RISK!!!

#region Check x64 host
    if( [System.IntPtr]::Size -ne 8) {
      Write-Error "Please use a x64 PowerShell host!"
      return
    }
#endregion

#region Load SharePoint SnapIn and DLL
  Remove-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
  Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
  
  #Check available SharePoint Cmdlets
  if( (Get-Command -Noun SPWeb*) -eq $null ) {
    Write-Error "SharePoint SnapIn not loaded. SharePoint cmdlets missing!"
    return
  }
#endregion

cls

$farm = [Microsoft.SharePoint.Administration.SPFarm]::Local

Get-SPServiceApplication | ? {$_.GetType().FullName -eq "Microsoft.Office.Server.Administration.SessionStateServiceApplication"} | Remove-SPServiceApplication 

$farm.Services | ? { $_.TypeName -like "*session state*" } | % {
  $_.Instances | % {
    $_.Delete()
  }
  $_.Delete()
}

Enumerate Sharepoint 2010 database in PowerShell

“Is there a way to enumerate all SharePoint 2010 databases in PowerShell like the page /_admin/DatabaseStatus.aspx”>/_admin/DatabaseStatus.aspx”>http://<centra_administration>/_admin/DatabaseStatus.aspx does it??”

YES!

You can use this script:

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint") 

$farm = [Microsoft.SharePoint.Administration.SPFarm]::Local

$type = ('Microsoft.SharePoint.Administration.SPPersistedTypeCollection`1') -as "Type"
$type = $type.MakeGenericType( ("Microsoft.SharePoint.Administration.SPDatabase"as "Type") )
$o = [Activator]::CreateInstance($type, $farm)

$’

Now the variable “o” contains all Database-Objects of your farm!

How to set the SharePoint 2010 Enterprise Search Service Application “Default Content Access Account” by using PowerShell

If you want to set the SharePoint 2010 Enterprise Search Service Application "Default Content Access Account" by using PowerShell you can use this script:

$searchapp = Get-SPEnterpriseSearchServiceApplication "Search Service Application"
$c= New-Object Microsoft.Office.Server.Search.Administration.Content($searchapp)
$c.SetDefaultGatheringAccount($crawlUser, (ConvertTo-SecureString $crawlPwd -AsPlainText -force))

($crawlUser is – of cause – the login of the account and $crawlPwd is the password in plain text)

How to embedd compressed scripts in other PowerShell scripts

For a current project I want to create a “master script” that contains another compressed PowerShell script. This compressed script contains some informations – server names, network share names – that should be as unreadable as possible for normal users. This script is executed during user logon.

I created two scripts

  1. "compress.ps1"
  2. "execute.ps1"

The first script is used to compress a script. The second one is used to execute the compressed script.

Here is the script for compressing:

 

cls

$c = Get-Content $$ -Encoding UTF8 

$r = [string]::Join("
", $c)

$r2 = [regex]::Match($r, "(.*)(#<--)(.*)", [System.Text.RegularExpressions.RegexOptions]::Singleline)

$ms = New-Object System.IO.MemoryStream
$cs = New-Object System.IO.Compression.GZipStream($ms, [System.IO.Compression.CompressionMode]::Compress)

$sw = New-Object System.IO.StreamWriter($cs)
$sw.Write($r2.Groups[3])
$sw.Close();

$bytes = $ms.ToArray()
[System.Convert]::ToBase64String($bytes)

exit
#<--

Write-Host "This is a test"
Get-Service A*

The script produces a base64 string that contains everything behind "#<–".

For the script above the output is:

H4sIAAAAAAAEAO29B2AcSZYlJi9tynt/SvVK1+B0oQiAYBMk2JBAEOzBiM3mkuwdaUcjKasqgcplVmVdZhZAzO2dvPfee++999577733ujudTif33/8/XGZkAWz2zkrayZ4hgKrIHz9+fB8/In7j5DdOvlsXbb797app04/ezIsmpf9laZs37Ue/cfJ53m6/zuvLYpqnx9/6jZP/By/6yuMxAAAA

Here is the execution script that contains this base64 string that represents
the compressed script:

cls

$data = [System.Convert]::FromBase64String("H4sIAAAAAAAEAO29B2AcSZYlJi9tynt/SvVK1+B0oQiAYBMk2JBAEOzBiM3mkuwdaUcjKasqgcplVmVdZhZAzO2dvPfee++999577733ujudTif33/8/XGZkAWz2zkrayZ4hgKrIHz9+fB8/In7j5DdOvlsXbb797app04/ezIsmpf9laZs37Ue/cfJ53m6/zuvLYpqnx9/6jZP/By/6yuMxAAAA")

$ms = New-Object System.IO.MemoryStream
$ms.Write($data, 0, $data.Length)
$ms.Seek(0,0) | Out-Null

$cs = New-Object System.IO.Compression.GZipStream($ms, [System.IO.Compression.CompressionMode]::Decompress)
$sr = New-Object System.IO.StreamReader($cs)
$t = $sr.readtoend()

Invoke-Expression $t

This executes the following code snipped from the script above:

Write-Host "This is a test"
Get-Service A*

The output is: 

This is a test

Status   Name               DisplayName                           
------   ----               -----------                           
Stopped  AeLookupSvc        Anwendungserfahrung                   
Running  AESTFilters        Andrea ST Filters Service             
Stopped  ALG                Gatewaydienst auf Anwendungsebene     
Stopped  AppIDSvc           Anwendungsidentität                   
Stopped  Appinfo            Anwendungsinformationen               
Running  Apple Mobile De... Apple Mobile Device                   
Stopped  AppMgmt            Anwendungsverwaltung                  
Stopped  aspnet_state       ASP.NET-Zustandsdienst                
Running  AudioEndpointBu... Windows-Audio-Endpunkterstellung      
Running  AudioSrv           Windows-Audio                         
Stopped  AxInstSV           ActiveX-Installer (AxInstSV)          

PowerShell: Cast Object Type

If you load an CSV file with import-csv you will end up with an object of type System.Management.Automation.PSCustomObject. It’s an array.

In such a case I liked to use such an imported file or especially the imported data with the correct object type.

Therefore I created an generic “cast” function in generic PowerShell that can be used for casting with other types.

See the following PowerShell script. The function “Get-CastedObject” takes to parameters:
1) the source array
2) the result object type as string

In the following sample the script creates a CSV file and reads the content of the file during the next run. After loading the data the objects of the array will be “casted” to the correct data type.

Therefore the cast function looks for the “property” object members and tries to assign them to the new created object of the expected result type.

I’m sure there are several opportunities for improvements. Please let me know!

$outfile = C:tempcast-test.csv

Add-Type @’
public class ResultObj
{
public string Test1 = “”;
public string Test2 = “”;
public bool   Test3 = false;
public int    Test4 = 0;
}
‘@

function Get-CastedObject
{
param(
[Parameter(Mandatory
=$true)] [object]$inputObject = $null,
[Parameter(Mandatory
=$true)] [string]$resultType = $null)

if($inputObject -isnot [System.Management.Automation.PSCustomObject] ) {
return $null
}

if($resultType -eq $null ) {
return $null
}

$resultObject = new-object $resultType

$inputObject |gm | ? {$_.MemberType -eq NoteProperty } |% {
Invoke-Expression $(`$resultObject.+$_.Name+ = `$inputObject.+$_.Name )
}

$resultObject
}

$ErrorActionPreference = Continue

if( @(get-childitem $outfile).count -gt 0 )
{
$global:imp = (Import-Csv -Delimiter ; -Path $outfile )
}

$l = @();

$imp | % {$l = $l + (Get-CastedObject $_ ResultObj)  }

$r = New-Object System.Random

for($i=0;$i -lt 10;$i++ ){
$obj = New-Object ResultObj
$obj.Test1 = Test + $l.Count.ToString()
$obj.Test2 = ([System.DateTime]::Now).ToString(HH:mm:ss)
$obj.Test3 = &{if( ($r.NextDouble())-lt 0.5 ) {$true }else {$false } }
$obj.Test4 = [int]$r.Next()
$l = $l + $obj
}

del $outfile -ErrorAction SilentlyContinue
$l |Export-Csv -Delimiter ; -Path $outfile -Encoding utf8 -Force -NoTypeInformation

Please notice my disclaimer in the right sidebar!

Activate Claim Based Authentication afterwards with PowerShell

You can active Claim Based Authentication for a SharePoint Web App afterwards if you missed that at creation time.

Use this PowerShell script:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
[System.Reflection.Assembly]::LoadFile($Env:CommonProgramFiles+"Microsoft SharedWeb Server Extensions14ISAPIMicrosoft.SharePoint.dll") | out-null

$webapp = Get-SPWebApplication "http://<sharepoint server>/"
write-host "Current: " $webapp.UseClaimsAuthentication
$webapp.UseClaimsAuthentication = $true
$webapp.Update()

$webapp.ProvisionGlobally()

write-host "    New: " $webapp.UseClaimsAuthentication

“TaxonomyPicker” failed to load – Error in Event Viewer

After updating the SharePoint Foundation 2010 Server of our company to SharePoint Server 2010 I got this error in the Event Viewer:

Load control template file /_controltemplates/TaxonomyPicker.ascx failed: 
Could not load type 'Microsoft.SharePoint.Portal.WebControls.TaxonomyPicker' 
from assembly 'Microsoft.SharePoint.Portal, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'.

I could solve this error by re-enabling the corresponding feature using this PowerShell script:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
[System.Reflection.Assembly]::LoadFile($Env:CommonProgramFiles+"Microsoft SharedWeb Server Extensions14ISAPIMicrosoft.SharePoint.dll") | out-null
Get-SPWebApplication -IncludeCentralAdministration | get-spsite | foreach-object { enable-spfeature "73ef14b1-13a9-416b-a9b5-ececa2b0604c" -force -url $_.Url -Verbose }

Note: The first to lines of the script enable are “standard lines of code” for me. They enable SharePoint PowerShell support if you use the Script without “SharePoint 2010 Management Shell”.