I'm working on Office 365 plugin in C# and trying this PowerShell command:
$newLicense = New-MsolLicenseOptions -AccountSkuId example:ENTERPRISEPACK -DisabledPlans SHAREPOINTWAC,MCOSTANDARD,SHAREPOINTENTERPRISE
Set-MsolUserLicense -UserPrincipalName [email protected] -AddLicenses "example:ENTERPRISEPACK" -LicenseOptions $newLicense
In PS, this works well. In C#, I'm having trouble to run this command. Here is my C# code, from PowerShellInvoker class:
var iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(new[] { MsOnline });
iss.ThrowOnRunspaceOpenError = true;
_runspace = RunspaceFactory.CreateRunspace(iss);
_runspace.Open();
_invoker = new RunspaceInvoke(_runspace);
I've tried many ways:
scriptText_ = "$newLicense = New-MsolLicenseOptions -AccountSkuId {1} -DisabledPlans SHAREPOINTWAC,MCOSTANDARD,SHAREPOINTENTERPRISE\n"+
"Set-MsolUserLicense -UserPrincipalName [email protected] -AddLicenses \"example:ENTERPRISEPACK\" -LicenseOptions $newLicense");
I use this following method to execute other commands which works perfectly:
_invoker.Invoke(scriptText_);
And also:
var pipeline = _runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText_);
return pipeline.Invoke(); // and getting back the variable
I also tried to add the variable in the Runspace object:
_runspace.SessionStateProxy.SetVariable ("newLicense", pipeline.Invoke());
But the command do not work, and returns no error. I don't really understand the PowerShell environment (I'm a beginner in this).
Thanks in advance for all the help you can provide.
Invoke? (This should help you identify if the variables are getting into the script.)var cmd = new Command("New-MsolLicenseOptions -AccountSkuId example:ENTERPRISEPACK -DisabledPlans SHAREPOINTWAC,MCOSTANDARD,SHAREPOINTENTERPRISE", true); cmd.Parameters.Add(variableName_, variableValue_); pipeline.Commands.Add(cmd); var result = pipeline.Invoke();and it fails. I really don't understand how C# correctly deals with variables (and parameters btw).$myVariablein the invoked command and check the right value comes back (ie. confirm that theSetVariableis working. Debugging: when stuck either your tools are limited or you're assuming something is working when it isn't and the latter is most likely.