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

时间:2010-10-18 16:31:55

标签: 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();

但是,如果我想对远程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();

2 个答案:

答案 0 :(得分: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");

Credential是c#PSCredential对象

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

答案 1 :(得分:1)

我会继续为Invoke-Command使用AddCommand(而不是AddScript)。添加Invoke-Command的参数,当你到达Scriptblock参数时,确保scriptblock定义了一个param()块,例如:

{param($cred) Set-HpcClusterProperty -InstallCredential $cred}

然后将ArgumentList参数添加到Invoke-Command命令,并将值设置为您创建的凭据。