2

I am trying to run an HPC cmdlet programmatically to change HPC install credential on a remote computer. If run the cmdlet locally, it's pretty straightforward:

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();

However, if I want to do the same thing with remote PowerShell, I need to run Invoke-Command and pass in the credential to the ScriptBlock inside the Command. How can I do that? It might look something like this, except I need to pass in the credential as an object binded to the InstallCredential parameter inside the ScriptBlock instead of a string:

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();
4

2 回答 2

9
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 对象

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

于 2012-12-14T09:55:38.027 回答
2

我会继续使用 AddCommand Invoke-Command(而不是 AddScript)。添加 Invoke-Command 的参数,当您获取Scriptblock参数时,确保脚本块定义了一个 param() 块,例如:

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

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

于 2010-10-18T18:13:38.597 回答