我想从C#应用程序中执行一个PowerShell脚本。该脚本必须在特定的用户上下文中执行。
我尝试了不同的场景,有些可以工作,有些不能:
1. 直接从PowerShell调用
我已经直接从运行在正确用户凭据下的ps控制台中调用了该脚本。
C:\Scripts\GroupNewGroup.ps1 1
结果: 脚本成功运行。
2. 从 c# 控制台应用程序中
我已经从一个以正确用户凭据启动的 c# 控制台应用程序中调用了该脚本。
代码:
string cmdArg = "C:\\Scripts\\GroupNewGroup.ps1 1"
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.ApartmentState = System.Threading.ApartmentState.STA;
runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(cmdArg);
pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
Collection<PSObject> results = pipeline.Invoke();
var error = pipeline.Error.ReadToEnd();
runspace.Close();
if (error.Count >= 1)
{
string errors = "";
foreach (var Error in error)
{
errors = errors + " " + Error.ToString();
}
}
结果:无法成功,并且出现了很多“空数组”异常。
3. 从C#控制台应用程序-代码方面模拟用户
(http://platinumdogs.me/2008/10/30/net-c-impersonation-with-network-credentials)
我已经从启动在正确用户凭据下的C#控制台应用程序中调用了该脚本,并且代码包含模拟用户。
代码:
using (new Impersonator("Administrator2", "domain", "testPW"))
{
using (RunspaceInvoke invoker = new RunspaceInvoke())
{
invoker.Invoke("Set-ExecutionPolicy Unrestricted");
}
string cmdArg = "C:\\Scripts\\GroupNewGroup.ps1 1";
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.ApartmentState = System.Threading.ApartmentState.STA;
runspace.ThreadOptions = PSThreadOptions.UseCurrentThread;
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(cmdArg);
pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
Collection<PSObject> results = pipeline.Invoke();
var error = pipeline.Error.ReadToEnd();
runspace.Close();
if (error.Count >= 1)
{
string errors = "";
foreach (var Error in error)
{
errors = errors + " " + Error.ToString();
}
}
}
结果:
- 'Get-Contact' 未被识别为 cmdlet、函数、脚本文件或可操作程序的名称。请检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试。
- 'C:\Scripts\FunctionsObjects.ps1' 未被识别为 cmdlet、函数、脚本文件或可操作程序的名称。请检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试。
- Windows PowerShell 版本2没有注册任何快照。Microsoft.Office.Server,Version=14.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c
- System.DirectoryServices.AccountManagement,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089
- 使用“1”个参数调用“.ctor”时出错:“找不到位于
http://XXXX/websites/Test4/
的 Web 应用程序。请确保您已正确输入 URL。如果该 URL 应提供现有内容,则系统管理员可能需要向预期的应用程序添加新的请求 URL 映射。” - 无法在空值表达式上调用方法。无法对空数组进行索引。
到目前为止还没有有效的答案。
有人知道为什么会有差异以及如何解决这个问题吗?