2

我正在从 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);
4

1 回答 1

0

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

您还可以查看此链接以获取一些示例。代码可能是这样的:

param(
      [parameter(Position=0, ValueFromPipeline=$true)][string]$username
      [parameter(Position=1, ValueFromPipeline=$true)][string]$path
     )
于 2012-08-15T15:12:07.223 回答