尝试在 C# 的 powershell 中执行以下操作
$certThumbrint = "someLocationToACert"
$cert = get-item $certThumbrint
Get-RoleInstanceCount -ServiceName "someServiceName" -DeploymentSlot "someSlot" -RoleName "someRole" -SubscriptionId "someId" -Certificate $cert
在 powershell 命令行中一一运行它们时,这非常有效。但我无法弄清楚如何通过代码来做到这一点。到目前为止,我已经做到了。
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.Add("$certThumbrint = \"someLocationToACert\"");
pipeline.Commands.Add(@"$cert = get-item $certThumbrint");
Command instanceCount = new Command("Get-RoleInstanceCount");
instanceCount.Parameters.Add(new CommandParameter("ServiceName", "someServiceName"));
....
instanceCount.Parameters.Add(new CommandParameter("Certificate", "$cert"));
然后我得到以下异常:
“术语 '$certThumbrint = “someLocation”' 未被识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,或者如果包含路径,请验证路径是否正确然后再试一次。
我尝试将变量添加为“AddScrips”,我也使用了
SessionStateVariableEntry var2 = new SessionStateVariableEntry("cert", "get-item $certThumbrint", "Initial session state MyVar1 test");
initialSessionState.Variables.Add(var2);
在创建运行空间之前。没有任何工作。还将所有代码添加到字符串中并尝试将其作为脚本运行。
我实际上没有办法做到这一点,感觉这是一件必须能够做到的非常简单的事情......谢谢。
编辑:还尝试了以下方法:
const string getInstanceCountScript = "$certThumbrint = \"somecert\" \n " +
"$cert = get-item $certThumbrint \n " +
"Get-RoleInstanceCount -ServiceName someservicename" +
...
" -Certificate $cert";
pipeline.Commands.AddScript(getInstanceCountScript);
它运行但返回一个空字符串。如果我将相同的代码放入我用“Add()”调用的 ps1 文件中,它就会运行并给我正确的输出。但我真的不想在我的项目中加载 ps1 文件,只需要 3 行或更少的代码。