我当前正在构建一个Windows服务,它将在某些请求传入时执行PowerShell命令。会有很多请求传入,因此我采用了来自Using Powershell RunspacePool multithreaded to remote server from C#的代码

我不使用WSManConnectionInfo,而是使用New-PSSession。请参阅本问题末尾的我的代码。

这似乎对所有常规命令都非常有效,但其中一个命令使用Exhange Cmdlet并在之前执行Import-PSSession。我不想每次运行脚本时都导入Cmdlet,但是我没有从C#中正确导入。调用后,PowerShell ErrorStream还注意到术语“Get-Mailbox”是未知的。我不明白为什么导入无效,我需要做什么。

我曾经工作过一次,但只有一个运行空间。移至RunspacePool后,我无法使其再次运行。

任何帮助将不胜感激。

编码:

static void Main(string[] args)
{
    string connectionUri = "https://.../Powershell";
    string userName = @"...\...";
    string password = "...";

    System.Uri uri = new Uri(connectionUri);
    System.Security.SecureString securePassword = String2SecureString(password);

    System.Management.Automation.PSCredential creds = new System.Management.Automation.PSCredential(userName, securePassword);

    //InitialSessionState iss = InitialSessionState.CreateDefault();
    //iss.ImportPSModule(new[] { "Get-Mailbox", "Get-MailboxStatistics" });

    RunspacePool runspacePool = RunspaceFactory.CreateRunspacePool();
    runspacePool.ThreadOptions = PSThreadOptions.UseNewThread;

    PowerShell powershell = PowerShell.Create();
    PSCommand command = new PSCommand();
    command.AddCommand(string.Format("New-PSSession"));
    command.AddParameter("ConfigurationName", "Microsoft.Exchange");
    command.AddParameter("ConnectionUri", uri);
    command.AddParameter("Credential", creds);
    command.AddParameter("Authentication", "Basic");
    command.AddParameter("AllowRedirection");

    // IS THIS NEEDED?
    PSSessionOption sessionOption = new PSSessionOption();
    sessionOption.SkipCACheck = true;
    sessionOption.SkipCNCheck = true;
    sessionOption.SkipRevocationCheck = true;
    command.AddParameter("SessionOption", sessionOption);

    powershell.Commands = command;

    runspacePool.Open();
    powershell.RunspacePool = runspacePool;
    Collection<PSSession> result = powershell.Invoke<PSSession>();

    foreach (ErrorRecord current in powershell.Streams.Error)
    {
        Console.WriteLine("Exception: " + current.Exception.ToString());
        Console.WriteLine("Inner Exception: " + current.Exception.InnerException);
    }

    // Returns the session
    if (result.Count != 1)
        throw new Exception("Unexpected number of Remote Runspace connections returned.");

    // THATS THE PART NOT WORKING
    // First import the cmdlets in the current runspace (using Import-PSSession)
    powershell = PowerShell.Create();
    command = new PSCommand();
    command.AddScript("Import-PSSession $Session -CommandName Get-Mailbox, Get-MailboxStatistics -AllowClobber -WarningAction SilentlyContinue -ErrorAction Stop -DisableNameChecking | Out-Null");
    command.AddParameter("Session", result[0]);

    // This is also strange... without the RunspaceInvoke I always get a SecurityException...
    RunspaceInvoke scriptInvoker = new RunspaceInvoke();
    scriptInvoker.Invoke("Set-ExecutionPolicy -Scope Process Unrestricted");

    var tasks = new List<Task>();

    for (var i = 0; i < 3; i++)
    {
        var taskID = i;
        var ps = PowerShell.Create();
        ps.RunspacePool = runspacePool;
        PSCommand cmd = new PSCommand();
        cmd.AddCommand(@".\PSScript1.ps1");
        //cmd.AddScript("Get-Mailbox -ResultSize 5");
        cmd.AddParameter("Session", result[0]);
        ps.Commands = cmd;
        var task = Task<PSDataCollection<PSObject>>.Factory.FromAsync(
                                             ps.BeginInvoke(), r => ps.EndInvoke(r));
        System.Diagnostics.Debug.WriteLine(
                          string.Format("Task {0} created", task.Id));
        task.ContinueWith(t => System.Diagnostics.Debug.WriteLine(
                          string.Format("Task {0} completed", t.Id)),
                          TaskContinuationOptions.OnlyOnRanToCompletion);
        task.ContinueWith(t => System.Diagnostics.Debug.WriteLine(
                          string.Format("Task {0} faulted ({1} {2})", t.Id,
                          t.Exception.InnerExceptions.Count,
                          t.Exception.InnerException.Message)),
                          TaskContinuationOptions.OnlyOnFaulted);
        tasks.Add(task);
    }

    Task.WaitAll(tasks.ToArray());
}

private static SecureString String2SecureString(string password)
{
    SecureString remotePassword = new SecureString();
    for (int i = 0; i < password.Length; i++)
        remotePassword.AppendChar(password[i]);

    return remotePassword;
}

简短的脚本:
Param($Session)

Import-PSSession $Session -CommandName Get-Mailbox, Get-MailboxStatistics -ErrorAction SilentlyContinue | Out-Null

Get-Mailbox -ResultSize 5 | SElectObject Name, Alias, ...

脚本的工作原理是这样的,但是当我尝试注释掉Import-PSSession部分时,我得到了未知的术语Get-Mailbox错误。

预先感谢和最诚挚的问候
pe

最佳答案

您需要取消对ISS东西的注释。做这样的事情:

$iss = [System.Management.Automation.Runspaces.InitialSessionState]::CreateDefault()
$iss.ImportPSModule($module)

将$ module替换为Exchange模块的名称,或仅使用模块名称填充变量。

然后,当您创建RunspacePool时,请执行以下操作:
$runspacePool = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspacePool($minRunspaces, $maxRunspaces, $iss, $Host)

这应该使模块可用于从运行空间池创建的所有运行空间。

07-25 22:52