从C#将多个变量传递给PowerShell

时间:2012-08-15 14:14:40

标签: c# powershell pipeline

我正在从C#调用PowerShell脚本,我正在使用哈希表来传递参数,但是在调用PowerShell脚本时,我得到了

  

找不到接受参数

的位置参数

PowerShell脚本有两个参数。哈希表有两个键,每个键有一个值。下面的PowerShell脚本:

param([string]$username,[string]$path)
#Gets SID
$objUser = New-Object System.Security.Principal.NTAccount($username)
$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$SID = $strSID.Value
# delets user
net user $username /DELETE
# removes folder
rmdir /q $path
Remove-Item -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\$SID"

调用PowerShell脚本的C#:

class RunScript
{
    public static void FireScript(String script, Hashtable var)
    {
        RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
        Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
        runspace.Open();
        RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);

    Pipeline pipeline = runspace.CreatePipeline();

    String scriptfile = "..\\..\\Resources\\" + script + ".ps1";

    Command myCommand = new Command(scriptfile, false);

    foreach (DictionaryEntry entry in var)
    {
        CommandParameter testParam = new CommandParameter(entry.Key.ToString(),entry.Value);

        //CommandParameter testParam = new CommandParameter(null, entry.Value);
        myCommand.Parameters.Add(testParam);
    }

    pipeline.Commands.Add(myCommand);
    Collection<PSObject> psObjects;
    psObjects = pipeline.Invoke();
    runspace.Close();
}
}

调用firescript的代码:

Hashtable var = new Hashtable();
var.Add("username","testb");
var.Add("path", "C:\\Documents and Settings\\testb");
RunScript.FireScript("remove user",var);

1 个答案:

答案 0 :(得分:0)

我认为您需要设置此参数属性:符合this link的ValueFromPipeline表示'可选的命名参数。 True表示cmdlet参数从管道对象获取其值。如果cmdlet访问完整对象而不仅仅是对象的属性,请指定此关键字。默认值为false。'

您也可以查看this link查看一些示例。代码可能是这样的:

param(
      [parameter(Position=0, ValueFromPipeline=$true)][string]$username
      [parameter(Position=1, ValueFromPipeline=$true)][string]$path
     )