【问题标题】:passing parameter to the powershell script file from C# environment从 C# 环境将参数传递给 powershell 脚本文件
【发布时间】:2012-02-17 22:43:35
【问题描述】:

我知道主题行看起来太普通了,并且有帖子解决了许多此类问题。我没有找到我真正想要的东西,因此这篇文章。

我正在从机器 A 调用要在远程机器(机器 B)上执行的 powershell 文件。

//这里是sn-p的代码:

 Runspace runspace = RunspaceFactory.CreateRunspace();
 runspace.Open();

Pipeline pipeline = runspace.CreatePipeline();
string scripttext = "$secpasswd = ConvertTo-SecureString '222_bbbb' -AsPlainText –Force";
string scripttext1 = "$mycreds = New-object -typename System.Management.Automation.PSCredential('TS-TEST-09\\Administrator',$secpasswd)";
string scripttext2  = "$s = New-PSSession -ComputerName TS-TEST-09 -Credential $mycreds";
**string scripttext5 = "Invoke-Command -Session $s -FilePath 'helper.ps1' | out-null";**

pipeline.Commands.AddScript(scripttext);
pipeline.Commands.AddScript(scripttext1);
pipeline.Commands.AddScript(scripttext2);
pipeline.Commands.AddScript(scripttext5);

Collection<PSObject> results = pipeline.Invoke();

现在排队 string scripttext5 = "Invoke-Command -Session $s -FilePath 'helper.ps1' | out-null"; 我必须将一些参数(例如,来自 c# 环境的用户名:useralias)传递给这个 helper.ps1 文件进行处理。任何人都可以指导我正确的方法吗?

TIA, 马尼什

【问题讨论】:

  • 任何带有完整源代码的最终解决方案?

标签: c# powershell parameters remoting powershell-remoting


【解决方案1】:

如果用户名和用户别名来自本地计算机,那么您可以这样做:

字符串 scripttext5 = "调用命令 -Session $s -FilePath 'helper.ps1' -Args " + 用户名 + "," + 用户别名 + " | Out-Null";

这假设您的 helper.ps1 文件至少有两个参数。如果是这样,那么 C# 变量 usernameuseralias 的值将被分配给前两个参数。

【讨论】:

  • 嗨 Keith ..您的假设对于这种情况是有效的 ..但是当我尝试这两个变量时,用户名本身作为“用户名”而不是此参数中包含的值提供。我什至在从-Args“+用户名+”中删除“”后也尝试过,但无济于事。我们能以某种方式纠正这种行为吗?
  • 应该可以,但如果不行,试试这个:string scripttext5 = String.Format("Invoke-Command -Session $s -FilePath 'helper.ps1' -Args {0},{1} | Out-Null", username, useralias);
【解决方案2】:

好的,这是对我有用的解决方案。

它从 Keith 的解决方案中汲取灵感。诀窍是使用 c# 公开变量

runspace.SessionStateProxy.SetVariable("PSuseralias", this.useralias);

现在使用 $PSuseralias 作为

string scripttext5 = "Invoke-Command -Session $s -FilePath 'helper.ps1' -Args  $PSuseralias;

这可以解决问题。

【讨论】:

    猜你喜欢
    • 2015-06-07
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    • 2021-12-12
    • 2014-01-07
    • 1970-01-01
    • 2019-10-22
    • 2021-08-26
    相关资源
    最近更新 更多