传递参数对象(PSCredential的)一个脚本块内的C#编程 [英] Pass a Parameter object (PSCredential) inside a ScriptBlock programmatically in C#

查看:257
本文介绍了传递参数对象(PSCredential的)一个脚本块内的C#编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图运行HPC编程cmdlet的改变HPC在远程计算机上安装证书。如果在本地运行该cmdlet,这是非常简单的:

 运行空间RS = GetPowerShellRunspace(); 
rs.Open();

管道管道= rs.CreatePipeline();
PSCredential的凭据=新PSCredential的(domainAccount,NEWPASSWORD);
指令CMD =新的Command(设置-HpcClusterProperty);
cmd.Parameters.Add(InstallCredential,证书);

pipeline.Commands.Add(CMD);

收集和LT; PSObject> RET = pipeline.Invoke();



不过,如果我想要做同样的事情与远程PowerShell,我需要运行调用命令并通过在凭证命令里面的脚本块。我该怎么办呢?它可能是这个样子,但我需要在凭证传递为绑定到脚本块,而不是一个字符串中的InstallCredential参数的对象:

 管道管线= rs.CreatePipeline(); 
PSCredential的凭据=新PSCredential的(domainAccount,NEWPASSWORD);

pipeline.Commands.AddScript(的String.Format(
CultureInfo.InvariantCulture,
调用命令-ComputerName {0} -ScriptBlock {{设置HpcClusterProperty -InstallCredential {1 }}},
节点名称,
证书));

收集和LT; PSObject> RET = pipeline.Invoke();


解决方案

我会继续使用AddCommand为调用命令(而不是AddScript)。添加参数调用命令,当你到了脚本块参数,确保脚本块定义了一个参数()块如:

  {参数($ CRED)设置HpcClusterProperty -InstallCredential $名气} 

然后添加参数列表参数设置为调用命令命令并将其值设置为凭证已创建的。


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

解决方案

I would continue to use AddCommand for Invoke-Command (instead of AddScript). Add the parameters for Invoke-Command and when you get to Scriptblock parameter, make sure the scriptblock defines a param() block e.g.:

{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.

这篇关于传递参数对象(PSCredential的)一个脚本块内的C#编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆