在C#中以编程方式在ScriptBlock中传递Parameter对象(PSCredential)

Chi*_*ang 2 c# powershell hpc

我试图以编程方式运行HPC cmdlet以更改远程计算机上的HPC安装凭据.如果在本地运行cmdlet,则非常简单:

Runspace rs = GetPowerShellRunspace();
rs.Open();

Pipeline pipeline = rs.CreatePipeline();
PSCredential credential = new PSCredential(domainAccount, newPassword);
Command cmd = new Command("Set-HpcClusterProperty");
cmd.Parameters.Add("InstallCredential", credential);

pipeline.Commands.Add(cmd);

Collection<PSObject> ret = pipeline.Invoke();
Run Code Online (Sandbox Code Playgroud)

但是,如果我想对远程PowerShell做同样的事情,我需要运行Invoke-Command并将凭证传递给Command内的ScriptBlock.我怎样才能做到这一点?它可能看起来像这样,除了我需要传递凭证作为绑定到ScriptBlock内的InstallCredential参数而不是字符串的对象:

Pipeline pipeline = rs.CreatePipeline();
PSCredential credential = new PSCredential(domainAccount, newPassword);

pipeline.Commands.AddScript(string.Format(
    CultureInfo.InvariantCulture,
    "Invoke-Command -ComputerName {0} -ScriptBlock {{ Set-HpcClusterProperty -InstallCredential {1} }}",
    nodeName,
    credential));

Collection<PSObject> ret = pipeline.Invoke();
Run Code Online (Sandbox Code Playgroud)

d.g*_*d.g 8

powershell.AddCommand("Set-Variable");
powershell.AddParameter("Name", "cred");
powershell.AddParameter("Value", Credential);

powershell.AddScript(@"$s = New-PSSession -ComputerName '" + serverName + "' -Credential $cred");
powershell.AddScript(@"$a = Invoke-Command -Session $s -ScriptBlock {" + cmdlet + "}");
powershell.AddScript(@"Remove-PSSession -Session $s");
powershell.AddScript(@"echo $a");
Run Code Online (Sandbox Code Playgroud)

Credential是c#PSCredential对象

我用它,也许它可以帮助你.