3

我目前正在构建一个 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 错误。

在此先感谢和最好的问候 Gope

4

2 回答 2

2

您需要取消注释 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)

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

于 2014-08-14T08:26:10.167 回答
0

我找到了一种让它工作的方法。我将 AddScript 更改为 AddCommand 并使用了 AddParameter。

// First import the cmdlets in the current runspace (using Import-PSSession)
powershell = PowerShell.Create();
powerShell.RunspacePool = runspacePool;
command = new PSCommand();
command.AddScript("Import-PSSession");
command.AddParameter("Session", result[0]);
command.AddParameter("CommandName", new[]{"Get-Mailbox", "Get-MailboxStatistics"});
command.AddParameter("ErrorAction ", "SilentlyContinue ");


powerShell.Invoke();

那成功了...

于 2014-08-14T09:42:30.860 回答