I have a ps1 script than runs fine when it is executed from powershell. It creates a user in Office365:
Param(
[string]$adminUser,
[string]$password,
[string]$adminSite,
[string]$userDisplayName,
[string]$userFirstName,
[string]$userLastName,
[string]$userPrincipalName,
[string]$userLicense,
[string]$userOffice,
[string]$userDepartment
)
try {
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client")
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Client.Runtime")
$executionPolicy = Get-ExecutionPolicy
Set-ExecutionPolicy RemoteSigned
$secpasswd = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($adminUser,$secpasswd)
Connect-MSolService -Credential $credential
#Write-Host "Conected to MSolService ..." -ForegroundColor Green
Connect-SPOService -Url $adminSite -Credential $credential # Here fail when running from .NET
#Write-Host "Conected to SP Online ..." -ForegroundColor Green
$user = New-MsolUser -FirstName $userFirstName -LastName $userLastName -UserPrincipalName $userPrincipalName -DisplayName $userDisplayName -LicenseAssignment $userLicenseAssignment -Office $userOffice -Department $userDepartment -UsageLocation ES
}catch [Exception] {
#Write-host "An Exception ocurred. The proccess is uncompleted" -ForegroundColor Red
#Write-Host $_.Exception.Message -ForegroundColor Red
Set-ExecutionPolicy $executionPolicy
return $false
}
Set-ExecutionPolicy $executionPolicy
return $user
It works. However, I have a C# program that executes this script in this way:
private Collection<PSObject> RunPsScriptFromFile(string psScriptPath, Dictionary<string, Object> parameters) {
if (!File.Exists(psScriptPath)) {
throw new FileNotFoundException("File not found.", psScriptPath);
}
Collection<PSObject> returnObjects = null;
using (Runspace runSpace = RunspaceFactory.CreateRunspace()) {
runSpace.Open();
RunspaceInvoke runSpaceInvoker = new RunspaceInvoke(runSpace);
Pipeline pipeLine = runSpace.CreatePipeline();
Command cmd = new Command(psScriptPath, false);
if (parameters != null && parameters.Count > 0) {
foreach (KeyValuePair<string, Object> p in parameters) {
CommandParameter cp = new CommandParameter(p.Key, p.Value);
cmd.Parameters.Add(cp);
}
}
pipeLine.Commands.Add(cmd);
returnObjects = pipeLine.Invoke();
}
return returnObjects;
}
This program works fine with others scripts, but for this one, I get the following error (at the line I've marked in the script):
The 'Connect-SPOService' command was found in the module 'Microsoft.Online.SharePoint.PowerShell', but the module could not be loaded. For more information, run 'Import-Module Microsoft.Online.SharePoint.PowerShell'.
I found a question about this, but without answer: Error running ps1 from c# code (Office 365)