![](/img/trans.png)
[英]How to Pass PSCredential object from C# code to Powershell Function
[英]Pass a Parameter object (PSCredential) inside a ScriptBlock programmatically in C#
我試圖以編程方式運行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();
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對象
我用它,也許它可以幫助你。
我會繼續使用AddCommand for Invoke-Command
(而不是AddScript)。 添加Invoke-Command的參數,當您獲得Scriptblock
參數時,請確保scriptblock定義了param()塊,例如:
{param($cred) Set-HpcClusterProperty -InstallCredential $cred}
然后將ArgumentList
參數添加到Invoke-Command
命令,並將值設置為您創建的憑據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.