我在C#中有一个PSCredential对象,并希望将其作为此Power
Shell脚本的参数传递
这是PSCredential对象
PSCredential Credential = new PSCredential ( "bla",blasecurestring)
这是我想在C#中运行的脚本
powershell.AddScript("$s = New-PSSession -ComputerName '" + serverName + "' -Credential " + Credential);
我无法理解这里提供的解决方案Pass a Parameter object (PSCredential) inside a ScriptBlock programmatically in C#
编辑:
这件事很有效
powershell.AddCommand("New-PSSession").AddParameter("ComputerName",serverName).AddParameter("Credential",Credential);
但是如何将会话信息保存在变量中呢?我需要它们用于以下命令:
powershell.AddScript(@"Invoke-Command -Session $s -ScriptBlock {" + cmdlet + "}");
解决方法
我现在找到了解决方案.当你知道你做了什么时,这很容易……
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对象