Search code examples
c#powershellsharepointpathpssnapin

Path for Add-PSSnapin not correct when running PowerShell Script from C#


I am running PowerShell Scripts from a C# Tool like this:

using (PowerShell pshell = PowerShell.Create())
{
    pshell.AddCommand(scriptFullPath);

    pshell.AddParameter("username", user);
    pshell.AddParameter("password", pass);

    PSDataCollection<PSObject> outputCollection = new PSDataCollection<PSObject>();
    PSInvocationSettings settings = new PSInvocationSettings();
    settings.ErrorActionPreference = ActionPreference.Stop;

    pshell.Invoke(null, outputCollection, settings);
}

Almost everything works fine in the Script until I need special Cmdlets from other Assemblies. The Add-PSSnapin Command will always fail with:

Exception: The Windows PowerShell snap-in 'Microsoft.SharePoint.Powershell' is not installed on this computer.
Exception: Cannot bind parameter 'Path' to the target. Exception setting "Path": "Cannot find path 'D:\dev\tool\Microsoft.SharePoint.dll' because it does not exist."

when running

$snapin = Get-PSSnapin | Where-Object {$_.Name -eq "Microsoft.SharePoint.Powershell"}
if ($snapin -eq $null)
{
    Write-Host "Loading SharePoint Powershell Snapin"
    Add-PSSnapin "Microsoft.SharePoint.Powershell"
    Add-Type -Path "Microsoft.SharePoint.dll" 
    Add-Type -Path "Microsoft.SharePoint.Runtime.dll"
}

Everything works fine when running the Script directly in a PowerShell window, so I guess it has something to do with the PATH or Scope that is not forwarded from the C# Tool. Playing around with the Parameter useLocalScope of AddCommand or other Parameters did not yield any results (although I am not sure if this has anything to do with paths).

How can I make the Script work and find external Assemblies?


Solution

  • The SharePoint PowerShell snapin is available in 64bit only. Your C# tool may be running as an x86 process, and therefore would give you the error "not installed". Also you may have to run the program "as Administrator" as some of the commands need that to work.

    The second error is, you're right, that there is no PATH variable set for SharePoint by default. The workaround is to specify the full path to the .dll, (and changing the version number for your install) e.g.

    Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.dll"