Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method with output parameters in PowerShell?

I'm working on a script to get started in PowerShell. I'm trying to convert a working VBScript script that enumerates mapped network drives on a remote Windows computer.

One of the tasks is to use remote WMI to read the registry and find the process owner of explorer.exe in order to determine who is logged in. This seems easy enough going by this guide.

However, the WMI method I need to call is GetOwner() from Win32_Process, which requires two output parameters to store its return value.

How can I call a method with output parameters? When I try to give it two strings, I get the error: Cannot find an overload for "GetOwner" and the argument count: "2".. The MSDN page says there are two parameters, so I'm not sure what I'm doing wrong.

like image 723
spoulson Avatar asked May 04 '09 20:05

spoulson


People also ask

How do you pass parameters to a function in PowerShell?

You can pass the parameters in the PowerShell function and to catch those parameters, you need to use the arguments. Generally, when you use variables outside the function, you really don't need to pass the argument because the variable is itself a Public and can be accessible inside the function.

How do you call a method in PowerShell?

To perform or "invoke" a method of an object, type a dot (.), the method name, and a set of parentheses "()". If the method has arguments, place the argument values inside the parentheses. The parentheses are required for every method call, even when there are no arguments.

What is param () in PowerShell?

The PowerShell parameter is a fundamental component of any script. A parameter is a way that developers enable script users to provide input at runtime. If a PowerShell script's behavior needs to change in some way, a parameter provides an opportunity to do so without changing the underlying code.

How do you pass by reference in PowerShell?

To pass a variable to a parameter that expects a reference, you must type cast your variable as a reference. The brackets and parenthesis are BOTH required.


Video Answer


1 Answers

Using the [ref] modifier:

SomeMethod( [ref] $a ); 

Notable blog entries

  • http://geekswithblogs.net/Lance/archive/2009/01/14/pass-by-reference-parameters-in-powershell.aspx
  • http://weblogs.asp.net/soever/archive/2009/03/26/powershell-return-values-from-a-function-through-reference-parameters.aspx
like image 109
JaredPar Avatar answered Oct 01 '22 17:10

JaredPar