I have to invoke a PowerShell global function from C# code:

using (Pipeline p = ...CreatePipeline())
{
Command c = new Command("MyFunction");
c.Parameters.Add("Name1", ...);
c.Parameters.Add("Name2", ...);
p.Commands.Add(c);
Collection<PSObject> result = p.Invoke();
...
}

(Question: is this way OK?)

Let MyFunction is:



function MyFunction ($Name1, $Name2)
{
$var1 = ...
...
}

Issue 1: $var1 becomes global after invocation of a function. I hardly want
it. Thus, I change my function:

function MyFunction ($Name1, $Name2)
{
&{
$var1 = ...
...
}
}

It looks now awkward, but it is OK, $var1 is now hidden in a local scope.

Issue 2: parameters $Name1, $Name2 become global variables after invocation.
It is pollution of variable name space. Data in $Name1, $Name2 consume
resources after the call. But the worst problem is that a user could have
his data stored as $Name1, $Name2. My call of MyFunction kills user's data.

Question: how do I call PowerShell functions with parameters from .NET to
avoid these issues?

--
Thanks,
Roman