从C#运行Powershell脚本出错

4

我有一个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时出错

你在 PowerShell 中运行了命令 "Import-Module Microsoft.Online.SharePoint.PowerShell" 吗?它应该提供一些信息。 - Matt
我已经做到了。无论如何,我在PowerShell中运行脚本没有任何问题,只有从C#代码中运行时出现问题。 - Jose Alonso Monge
2个回答

3

我修改了我的C#代码:

pipeLine.Commands.Add(cmd);
returnObjects = pipeLine.Invoke();
var error = pipeLine.Error.ReadToEnd(); // New line

"error"变量包含以下内容:

当前处理器架构为X86。'C:\Program Files\SharePoint Online Management Shell\Microsoft.Online.SharePoint.PowerShell\Microsoft.Online.SharePoint.PowerShell.psd1'模块需要Amd64架构。

我已经找到这个文件并更改了这一行。

# Processor architecture (None, X86, Amd64, IA64) required by this module
ProcessorArchitecture = 'Amd64'

针对这个问题:

# Processor architecture (None, X86, Amd64, IA64) required by this module
ProcessorArchitecture = 'X86'

我不知道这是否是一个好的解决方案,但它可以工作。我会继续寻找其他方案。 欢迎提出任何建议。


0

C:\Users\<your user>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Windows PowerShell 中,有两个版本的PowerShell,一个是x86版本,另一个是AMD64版本,没有后缀名。

旧版本的模块只写了32位,包括最新的SharePoint Online在内的新版本只写了64位。

如果您在32位环境中启动它,显然不会运行任何64位模块,在一些边缘情况下,您需要运行旧的32位来运行非常旧的模块。

更好的解决方案是调用您的PowerShell脚本 %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -command "script.ps1"

我猜您首先找到的是syswow 32位版本。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接