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