Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PowerShell class to invoke a "[namespace.class]::method" style command

I created a powershell object via .net to invoke commands. When I invoke normal commands like 'Get-Process' I had no problems:

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").

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

like image 995
Marco Avatar asked May 25 '26 00:05

Marco


1 Answers

You need to add script to the pipeline since calling out to .NET requires script i.e. .NET methods are not considered PowerShell commands e.g.:

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);
     }
}
like image 126
Keith Hill Avatar answered May 26 '26 16:05

Keith Hill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!