3

私は現在、PowerShell コマンドを実行する Windows サービスを構築しています。このサービスは、いくつかの要求が入ってきた場合に実行されます。多くの要求が来るので、次のコードを採用しました: Using Powershell RunspacePool multithreaded to remote server from C#

私は WSManConnectionInfo を使用していませんが、New-PSSession だけを使用しています。この質問の最後にある私のコードを参照してください。

これは、すべての通常のコマンドでうまく機能するように見えますが、Exhange コマンドレットを使用し、以前に Import-PSSession を実行するものです。スクリプトを実行するたびにコマンドレットをインポートしたくありませんが、C# から正しくインポートできません。呼び出し後、PowerShell ErrorStream は、"Get-Mailbox" という用語が不明であることにも注意します。インポートが機能しない理由と、そのために何をする必要があるのか​​ わかりません。

私は一度だけ働いていましたが、実行空間は 1 つしかありませんでした。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 エラーが発生します。

よろしくお願いします。

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 に答える