简体   繁体   English

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

[英]Pass a Parameter object (PSCredential) inside a ScriptBlock programmatically in C#

I am trying to run an HPC cmdlet programmatically to change HPC install credential on a remote computer. 我试图以编程方式运行HPC cmdlet以更改远程计算机上的HPC安装凭据。 If run the cmdlet locally, it's pretty straightforward: 如果在本地运行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();

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. 但是,如果我想对远程PowerShell做同样的事情,我需要运行Invoke-Command并将凭证传递给Command内的ScriptBlock。 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: 它可能看起来像这样,除了我需要传递凭证作为绑定到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();
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");

Where Credential is the c# PSCredential object Credential是c#PSCredential对象

I use this, maybe it can help you. 我用它,也许它可以帮助你。

I would continue to use AddCommand for Invoke-Command (instead of AddScript). 我会继续使用AddCommand for Invoke-Command (而不是AddScript)。 Add the parameters for Invoke-Command and when you get to Scriptblock parameter, make sure the scriptblock defines a param() block eg: 添加Invoke-Command的参数,当您获得Scriptblock参数时,请确保scriptblock定义了param()块,例如:

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

Then add the ArgumentList parameter to the Invoke-Command command and set the value to the credential you have created. 然后将ArgumentList参数添加到Invoke-Command命令,并将值设置为您创建的凭据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM