我有一个ps1脚本,当它从powershell中执行时可以正常运行。它在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
它有效。 然而,我有一个以C#编写的程序,以这种方式执行该脚本:
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;
}
这个程序可以与其他脚本一起正常工作,但是对于这个脚本,我在标记的行处遇到了以下错误:
“Connect-SPOService”命令在模块“Microsoft.Online.SharePoint.PowerShell”中找到,但无法加载该模块。有关更多信息,请运行“Import-Module Microsoft.Online.SharePoint.PowerShell”。
我找到了一个相关问题,但没有答案: 从C#代码(Office 365)运行ps1时出错