PowerShell x64 vs x86: set execution policy when using Visual Studio post build events

Running PowerShell scripts in the Post build events within a Visual Studio project? Getting errors telling you “running scripts is disabled on this system”?

Visual Studio Output window showing PowerShell execution error

While working on Office 365 Developer Patterns and Practices (PnP) solution OfficeDevPnP.PowerShell Commands I had troubles with building my solution. Visual Studio uses PowerShell x86 in the background instead of my default PowerShell which uses the x64 version.

Check PowerShell version: x64 versus x86

By running the following you can check the current version. Download the PowerShell function from Check-PSVersion.ps1

function Check-PSVersion { if ([System.IntPtr]::Size -eq 4) { # When equal to 4, then x86 Write-Host "Running x86 PowerShell session" } else { # When equal to 8, then x64 Write-Host "Running x64 PowerShell session" } } Check-PSVersion

Where to find the PowerShell executable for both x64 and x86

The x64 version of PowerShell (Windows 8.1) can be found under:

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"

The x86 version of PowerShell (Windows 8.1) can be found under:

"C:\Windows\syswow64\WindowsPowerShell\v1.0\powershell.exe"

Change execution policy to use PowerShell in Visual Studio

Now we know we have two versions of PowerShell we can change the execution policy for the x86 version of PowerShell. Start the "C:\Windows\syswow64\WindowsPowerShell\v1.0\powershell.exe" with “Run as administrator”. Now change the execution policy accordantly.

Set-ExecutionPolicy Unrestricted

Developing hybrid SharePoint apps that run on-premise and in the cloud – ESPC 2014

My session at the European SharePoint Conference (#ESPC14) was around developing hybrid apps with the SharePoint App Model. Below you can find the slide deck and PowerShell scripts I used during the demo.

Before you start building hybrid apps who are depending on the authentication done by Azure Control Services (ACS) you need to setup a trust between your on-premise farm and ACS.

  1. Replace the default STS certificate and reboot machine afterwards (Replace-STSCertificate.ps1)
  2. Install Microsoft Online Services Sign-In Assistant for IT Professionals RTW (64-bit), http://www.microsoft.com/en-us/download/details.aspx?id=41950
  3. Install Microsoft Online Services Module for Windows PowerShell (64-bit), http://go.microsoft.com/fwlink/p/?linkid=236297
  4. Run script to connect on-premise SharePoint farm to ACS (Connect-SPFarmToAAD.ps1)

Some important side notes:

  • When replacing the STS certificate, all current trusts who are depending on the STS become invalid. Meaning you have to recreate your existing Trusted Security Token Issuers (Install-TrustedSecurityTokenIssuer.ps1 & Remove-TrustedSecurityTokenIssuer.ps1)
  • Ensure you are using the RTW version of Microsoft Online Services Sign-In Assistant instead of the BETA (which is linked in the TechNet article)

Download PowerShell scripts.

Scripts originate from How to: Use an Office 365 SharePoint site to authorize provider-hosted apps on an on-premises SharePoint site (http://msdn.microsoft.com/en-us/library/office/dn155905(v=office.15).aspx), I don’t own the scripts but only provide them for easy of use.

Ping, nslookup and ipconfig cmd via PowerShell

I’m used to regularly work with ping.exe, nslookup.exe and ipconfig.exe in the command prompt. With PowerShell becoming more and more the default it’s time to change my default behavior, sounds like a real programmer…

PowerShell 4.0 provides cmdlets for these commonly used command-line executables. Since I’m often searching for the cmdlet name, I thought to write a personal reminder and share it with you!

Another nice cmdlet to retrieve your IP addresses is:

Get disk storage for SharePoint databases

To get an indication for all database sizes in your SharePoint farm, run the following command. It shows the disk storage in bytes and MB.

image

The PowerShell script used for the output above, can be found below.

Add-PSSnapin Microsoft.SharePoint.PowerShell Get-SPDatabase | sort Name | ft Name, ` @{Name="DiskSizeRequired";Align='Right';Expression={[string]("{0:N0}" -f($_.DiskSizeRequired))}}, ` @{Name="Size(MB)";Align='Right';Expression={[string]("{0:N0}" -f($_.DiskSizeRequired/1mb))}}, ` Server -Autosize Get-SPDatabase | sort Name | select Name, DiskSizeRequired ` | measure-object -Property DiskSizeRequired -Sum -Maximum -Minimum -Average ` | ft Count, @{Name="Sum(MB)";Align='Right';Expression={[string]("{0:N0}" -f($_.Sum/1mb))}}, ` @{Name="Maximum(MB)";Align='Right';Expression={[string]("{0:N0}" -f($_.Maximum/1mb))}}, ` @{Name="Minimum(MB)";Align='Right';Expression={[string]("{0:N0}" -f($_.Minimum/1mb))}}, ` @{Name="Average(MB)";Align='Right';Expression={[string]("{0:N0}" -f($_.Average/1mb))}}

Using CSOM and PowerShell to query SharePoint Online or on-premise

Recently I released the SharePoint Client Browser (preview) that provides inside in a remote SharePoint site by using the Client Side Object Model (CSOM). The tool only reads data and shows it in a rich interface. When you want to make changes you have options: 1) build a custom tool and use the CSOM to interact with SharePoint or 2) use PowerShell and CSOM to interact with SharePoint.

This post shows how to use PowerShell and CSOM together to interact and automate configuration changes to your SharePoint. The example script can be used for both SharePoint Online and on-premise deployments.

This PowerShell script will be a new feature in the SharePoint Client Browser. This allows the user to start PowerShell directly from the SharePoint Client Browser and eliminates the need to do the scripting discussed in this post by yourself!

Prerequisites

Besides having a SharePoint site collection somewhere, you need to create a folder on your local machine. This folder needs to have the SharePoint Client Runtime assemblies. These can be downloaded here. Next to the SharePoint Client Runtime you need to place your scripts here (for example: OpenSite.ps1).

Folder (on local machine) with prerequisites

The PowerShell script

The easiest way to get started is creating a new TXT-file in the local folder and rename it to “OpenSite.ps1” (or choose a more appropriate name). Next right click with your mouse on the file and choose Edit. This will open up the Windows PowerShell ISE and you can start editing your script.

Authentication

The script is pretty easy and almost reusable for both SharePoint Online and on-premise, but it has a difference between them. Guest what it is?! The authentication is done differently. Below 3 different authentication examples.

Current user credentials

By not providing any credentials automatically the current user credentials are used.

SharePoint Online

When connecting to SharePoint Online you can use the new SharePointOnlineCredentials class. This makes it a lot easier then with SharePoint 2010.

$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl) $ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($loginname, $pwd)

SharePoint (on-premise) and credentials

Setting the credentials is done via the NetworkCredential class. That looks like this:

$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl) $ctx.Credentials = New-Object System.Net.NetworkCredential($loginname, $pwd)

The full example script

Below you can find the PowerShell script to use with SharePoint Online. Make sure when using the script you choose the right authentication model (see above). After running this script you can use the CSOM the same way as you would use CSOM in your C# application.

$loc = "C:\Users\Bram\Downloads\SharePoint" # Location of DLL's $siteUrl = "https://contoso.sharepoint.com" $loginname = "bram@contoso.onmicrosoft.com" Set-Location $loc Add-Type -Path (Resolve-Path "Microsoft.SharePoint.Client.dll") Add-Type -Path (Resolve-Path "Microsoft.SharePoint.Client.Runtime.dll") Write-Host "Please enter password for $($siteUrl):" $pwd = Read-Host -AsSecureString $ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl) # Remove or replace line below to change authentication method $ctx.Credentials = New-Object System.Net.NetworkCredential($loginname, $pwd) $web = $ctx.Web $ctx.Load($web) $ctx.ExecuteQuery() Write-Host " Current web title is '$($web.Title)', $($web.Url)"

Slide deck and demos SharePoint Saturday 2013 Holland (#SPSNL13)

Last Saturday I presented at the SharePoint Saturday Holland 2013. It was a good vibe and the audience made it an interactive session. Below you can find the slide deck and parts of PowerShell scripts and source code which I used during my demos.

SharePoint Saturday Holland 2013

Developing hybrid SharePoint apps that run on-premise and in the cloud

With the new SharePoint App model running outside the SharePoint worker process it introduces new authentication models. As a developer you don’t want to build multiple versions of the same app implementing each authentication model separately. This session explains the differences between securing SharePoint apps with OAuth in Office 365 and S2S High Trust in on-premise deployments. You will learn how to build a single app that will run on-premise, online and hybrid SharePoint environments.

Demo: Configure the on-premise SharePoint with Trusted Security Token Issuer

To support high-trust (S2S) apps you need to configure the Trusted Security Token Issuer in your on-premise SharePoint farm. This script is used during the demo to configure the SharePoint farm.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ea 0 # Get the .cer file that you want to use with your app. $certificate = Get-PfxCertificate "C:\Apps\AppCertSP2013.cer" # Get the issuer ID of your app. All the letters in the issuer ID GUID must be lowercase. $issuerId = 'a58e2347-0ead-4ba0-b4b7-75120aa09e4e' # Get the current authentication realm for your SharePoint site $realm = Get-SPAuthenticationRealm -ServiceContext "http://vm-sp-01/sites/dev" # Get the issuer ID together with the realm value. $fullIssuerIdentifier = $issuerId + '@' + $realm # Create a trusted security token service. This fetches metadata from your app (for example, the certificate) and establishes trust with it, so that SharePoint 2013 can accept tokens that are issued by your app. New-SPTrustedSecurityTokenIssuer -Name $issuerId -Certificate $certificate -RegisteredIssuerName $fullIssuerIdentifier –IsTrustBroker

Demo: Build Hybrid app with a single codebase for on-premise and cloud

My last demo was building a Hybrid app that consists of a single codebase which runs both on-premise and in the cloud. The logic which determines if SharePoint is hosted in on-premise or in the cloud is below.

public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Uri hostWeb = new Uri(Request.QueryString["SPHostUrl"]); string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request); if (string.IsNullOrEmpty(contextTokenString)) { using (var clientContext = TokenHelper.GetS2SClientContextWithWindowsIdentity(hostWeb, Request.LogonUserIdentity)) { clientContext.Load(clientContext.Web, web => web.Title); clientContext.ExecuteQuery(); Response.Write(clientContext.Web.Title); } } else { using (var clientContext = TokenHelper.GetClientContextWithContextToken(hostWeb.OriginalString, contextTokenString, Request.Url.Authority)) { clientContext.Load(clientContext.Web, web => web.Title); clientContext.ExecuteQuery(); Response.Write(clientContext.Web.Title); } } } }

In search of PowerShell environment variables

When working with PowerShell I’m searching for the same variables over and over again. Every time when I found them again I think the same “Oh yeah, I knew that!”. To minimize my search next time I thought about writing it down.

First question, how do I use these variables? This is pretty straightforward.

$Env:username

Second question, which environment variables can I use? Use the following cmdlet:

Get-Item Env: | sort Name Name Value ---- ----- COMPUTERNAME <computername> HOMEPATH \Users\sa-sp2010-Install LOCALAPPDATA C:\Users\sa-sp2010-Install\AppData\Local PSModulePath D:\SPInstall\SPModule;D:\SPInstall\SPModule;C:\Users\sa-sp2010-Install\Documents\Windows... PROCESSOR_ARCHITECTURE AMD64 CommonProgramW6432 C:\Program Files\Common Files CommonProgramFiles(x86) C:\Program Files (x86)\Common Files ProgramFiles(x86) C:\Program Files (x86) PROCESSOR_LEVEL 6 windows_tracing_flags 3 USERNAME sa-sp2010-Install HOMEDRIVE C: USERPROFILE C:\Users\sa-sp2010-Install SystemRoot C:\Windows TEMP C:\Users\SA-SP2~1\AppData\Local\Temp PUBLIC C:\Users\Public ALLUSERSPROFILE C:\ProgramData APPDATA C:\Users\sa-sp2010-Install\AppData\Roaming ProgramData C:\ProgramData PATHEXT .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC OS Windows_NT CommonProgramFiles C:\Program Files\Common Files PROCESSOR_IDENTIFIER Intel64 Family 6 Model 23 Stepping 10, GenuineIntel ComSpec C:\Windows\system32\cmd.exe SystemDrive C: PROCESSOR_REVISION 170a ProgramFiles C:\Program Files NUMBER_OF_PROCESSORS 2 windows_tracing_logfile C:\BVTBin\Tests\installpackage\csilogfile.log TMP C:\Users\SA-SP2~1\AppData\Local\Temp ProgramW6432 C:\Program Files Path C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPower... USERDOMAIN <DOMAIN> VS100COMNTOOLS C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools\ windir C:\Windows