【问题标题】:PowerShell commandlet getting invoked but not respondingPowerShell commandlet 被调用但没有响应
【发布时间】:2014-09-01 08:27:30
【问题描述】:

Invoke-MyFunction 是我编写的一个命令行开关,它接受一个输入文件,对其进行更改,然后在指定位置创建一个新的输出文件。如果我在桌面上打开 PowerShell,导入 MyCommandlet.ps1,然后运行 ​​

Invoke-MyFunction -InputPath path\to\input -OutputPath path\to\output

一切都按预期进行。但是,当我尝试使用以下代码从 C# 程序导入和调用命令时,命令行开关不会运行,不会记录输出,也不会生成输出文件。它不会抛出 CommandNotFoundException,因此我假设 PowerShell 对象可以识别我的命令行开关。但我不知道为什么它不执行它。

    //set up the PowerShell object
    InitialSessionState initial = InitialSessionState.CreateDefault();
    initial.ImportPSModule(new string[] { @"C:\path\to\MyCommandlet.ps1" });
    Runspace runspace = RunspaceFactory.CreateRunspace(initial);
    runspace.Open();
    PowerShell ps = PowerShell.Create();
    ps.Runspace = runspace;

    //have MyFunction take input and create output
    ps.AddCommand("Invoke-MyFunction");
    ps.AddParameter("OutputPath", @"C:\path\to\output");
    ps.AddParameter("InputPath", @"C:\path\to\input");
    Collection<PSObject> output = ps.Invoke();

此外,调用 MyFunction 后,PowerShell 对象 ps 无法执行任何其他命令。甚至是已知的。

【问题讨论】:

  • 我尝试过调用Copy-Item 而不是Invoke-MyFunction,这是可行的。所以我假设是关于Invoke-MyFunction 的东西导致了这个问题。

标签: c# visual-studio powershell cmdlets


【解决方案1】:

这对我有用:

//set up the PowerShell object
var initial = InitialSessionState.CreateDefault();
initial.ImportPSModule(new string[] { @"C:\Users\Keith\MyModule.ps1" });
Runspace runspace = RunspaceFactory.CreateRunspace(initial);
runspace.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = runspace;

//have MyFunction take input and create output
ps.AddCommand("Invoke-MyFunction");
ps.AddParameter("OutputPath", @"C:\path\to\output");
ps.AddParameter("InputPath", @"C:\path\to\input");
var output = ps.Invoke();
foreach (var item in output)
{
    Console.WriteLine(item);
}

MyModule.ps1 为:

function Invoke-MyFunction($InputPath, $OutputPath) {
   "InputPath is '$InputPath', OutputPath is '$OutputPath'"
}

确实导致我失败的一件事是,在 Visual Studio 2013(也可能是 2012 年)上,AnyCPU 应用程序实际上将在 64 位操作系统上运行 32 位。您必须为 PowerShell x86 设置执行策略才能允许脚本执行。尝试在管理员模式下打开 PowerShell x86 shell 并运行 Get-ExecutionPolicy。如果设置为Restricted,则使用Set-ExecutionPolicy RemoteSigned 允许脚本执行。

【讨论】:

  • 事实证明,对我来说,问题是 MyCommandlet.ps1 中的错误,而不是我的 C# 代码中的错误。我没有注意到的是 Invoke-MyFunction 仅在从某个目录调用时才有效(因为它依赖的某些文件位于该目录中)。从 C# 调用它,工作目录是错误的,这就是它失败的原因。解决方案是更改命令行开关以便可以从任何地方调用它。
  • 很高兴听到您弄明白了。
猜你喜欢
  • 1970-01-01
  • 2022-07-06
  • 1970-01-01
  • 1970-01-01
  • 2012-04-25
  • 1970-01-01
  • 1970-01-01
  • 2012-02-07
  • 1970-01-01
相关资源
最近更新 更多