简体   繁体   English

使用PowerShell类调用“[namespace.class] :: method”样式命令

[英]Using PowerShell class to invoke a “[namespace.class]::method” style command

I created a powershell object via .net to invoke commands. 我通过.net创建了一个powershell对象来调用命令。 When I invoke normal commands like 'Get-Process' I had no problems: 当我调用像'Get-Process'这样的常规命令时,我没有遇到任何问题:

ps.AddCommand("Get-Process").AddParameter(...).Invoke()

but I'm not able to invoke a .net method with the syntax "[namespace.class]::method", just to make an example to invoke [System.IO.File]::Exists("c:\\boo.txt"). 但我无法使用语法“[namespace.class] :: method”调用.net方法,只是为了调用[System.IO.File] :: Exists(“c:\\ boo。文本”)。

I tried with 我试过了

ps.AddCommand("[System.IO.File]::Exists(\"c:\\boo.txt\")").Invoke()

ps.AddCommand("[System.IO.File]::Exists").AddArgument("c:\\boo.txt").Invoke()

and some others. 和其他一些人。 It always throws an exception which says that the command specified is not recognized. 它总是抛出一个异常,表示无法识别指定的命令。

There is a way to invoke that type of command? 有一种方法可以调用那种类型的命令吗? Thanks 谢谢

You need to add script to the pipeline since calling out to .NET requires script ie .NET methods are not considered PowerShell commands eg: 您需要向管道添加script ,因为调用.NET需要脚本,即.NET方法不被视为PowerShell commands例如:

static void Main()
{
     PowerShell ps = PowerShell.Create();
     ps.AddScript(@"[IO.File]::Exists('C:\Users\Keith\foo.txt')");
     foreach (PSObject result in ps.Invoke())
     {
         Console.WriteLine(result);
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM