Running powershell within a SharePoint application page (C#)
-
16-10-2019 - |
Question
I have a feature that deploys an application page to the layouts directory. I am attempting to update the content (or config?) database by executing a powershell command from c#.
The following code will execute fine and give me the current status of the developer dashboard (on,off,ondemand).
PowerShell ps = PowerShell.Create();
ps.AddScript("Add-PsSnapin Microsoft.SharePoint.Powershell");
ps.AddScript("$svc=[Microsoft.SharePoint.Administration.SPWebService]::ContentService");
ps.AddScript("$ddsetting=$svc.DeveloperDashboardSettings");
ps.AddScript("$ddsetting.DisplayLevel");
System.Collections.ObjectModel.Collection<string> output = ps.Invoke<string>();
I am attempting to update this setting.
PowerShell ps = PowerShell.Create();
ps.AddScript("Add-PsSnapin Microsoft.SharePoint.Powershell");
ps.AddScript("$svc=[Microsoft.SharePoint.Administration.SPWebService]::ContentService");
ps.AddScript("$ddsetting=$svc.DeveloperDashboardSettings");
ps.AddScript(string.Format("$ddsetting.DisplayLevel=[Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::{0}", rblDashboard.SelectedValue));
ps.AddScript("$ddsetting.Update()");
ps.Invoke<string>();
I can step through the code just fine, but the setting is never updated. The string.format
line evaluates as I'd expect. That value is changed like it should.
Solution
I guess there will be ok to run Powershell from SharePoint, but why will you not use managed code for this? Powershell is great for scripting, but most of the commands can also be found in managed code.
The Microsoft.SharePoint.Administration.SPDeveloperDashboardSettings class can help.
SPDeveloperDashboardSettings settings =
SPWebService.ContentService.DeveloperDashboardSettings;
settings.DisplayLevel = SPDeveloperDashboardLevel.On;
settings.TraceEnabled = true;
settings.Update();