简体   繁体   中英

Launching SharePoint Management Shell (PowerShell) From C#

I am attempting to programmatically launch the SharePoint Management Shell from C# code and I am getting different behavior that when I select it from the Start Menu. I have attempted to do this two different ways with the same result:

Attempt #1:

var startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.Verb = "runas";
startInfo.FileName = "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\PowerShell.exe";
startInfo.Arguments = "-NoExit \"  & 'C:\\Program Files\\Common Files\\Microsoft Shared\\Web Server Extensions\\14\\CONFIG\\POWERSHELL\\Registration\\sharepoint.ps1' \"";
Process.Start(startInfo);

Attempt #2:

var startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.Verb = "runas";
startInfo.FileName = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Microsoft SharePoint 2010 Products\\SharePoint 2010 Management Shell.lnk";
Process.Start(startInfo);

Both of these methods launch a PowerShell window and display the following error message:

File C:\\Program Files\\Common Files\\Microsoft Shared\\Web Server Extensions\\14\\CO NFIG\\POWERSHELL\\Registration\\SharePoint.ps1 cannot be loaded because the execut ion of scripts is disabled on this system. Please see "get-help about_signing" for more details. At line:1 char:3 + & <<<< ' C:\\Program Files\\Common Files\\Microsoft Shared\\Web Server Extensio ns\\14\\CONFIG\\POWERSHELL\\Registration\\sharepoint.ps1 ' + CategoryInfo : NotSpecified: (:) [], PSSecurityException + FullyQualifiedErrorId : RuntimeException

When I launch it from the Start Menu, it works just fine. Any ideas on why this behaves differently? In Attempt #1 I am running the same executable and arguments as the Link. In Attempt #2 I am trying to run the link itself.

Thanks!

This problem is usually caused by x86 and x64 PowerShell each requiring ExecutionPolicy to be set to something other than Restricted in order to run scripts. Perhaps your PowerShell console is x64 and your C# program is running as x86 or vice-versa. Either way, pass in an additional parameter to PowerShell -ExecutionPolicy ByPass to skip past this particular problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM