calling Invoke-Expression with Parameters in Powershell - c#

I've written a powershell module in c# that has a bunch of cmdlets like
Add-VM
The cmdlets reach out to an API and pull data back.
but for the sake of uniformity with the ssh CLI of the product, i've written a function called newtask that accepts 'addvm' as an argument and $args.
for example
newtask addvm -id 12345
I then invoke Add-VM and pass $args as a string like so
Invoke-Expression Add-VM $argstr
The problem is that Add-VM throws an error that it cannot find a positional parameter that accepts argument System.Object[]
A positional parameter cannot be found that accepts argument 'System.Object[]'
While I could easily alias 'addvm' to 'Add-VM', i'm trying to maintain uniformity with the ssh CLI so that new users can quickly start utilizing this module.
I figured that sending a string like '-id 12345' would suffice but it's not. Does the pscmdlet expect to receive something else?
Thanks in advance.

I know this is a little old now, but I was having a similar issue and a co-worker showed me that escaping $argstr prevents the object from getting converted to a string.
Invoke-Expression "Add-VM `$argstr"

That error is from Invoke-Expression not Add-VM and you just need quotes around the argument:
Invoke-Expression "Add-VM $argstr"
This has the drawback of forcing all objects into string format. This might be acceptable for simple types like ints and strings but if you want to pass through a more complex object it won't work. An alternative would be to splat the arguments with #args but I don't think you can do this through Invoke-Expression or Invoke-Command. You need to directly call the cmdlet:
function newtask {
params([string]$command)
switch ($command) {
"addvm" { Add-VM #args }
"deletevm" { Remove-VM #args }
}
}

Related

c# MongoDB RunCommand

Can someone give me an example of the use of the RunCommand method that takes a string argument only (called CommandName) available in the MongoDB .NET driver? I know there is an overloaded RunCommand method that takes an object reference (I think a CommandDocument object) as an argument, but I'd rather not use that one.
I'm having trouble getting the syntax right for CommandName. Thanks in advance!
If you are using some recent version of the official C# driver, the "real" string based version you are referring to (CommandResult RunCommand(string commandName)) is only part of the legacy driver component (check the namespace). I would hence not recommend using it.
The "official" interface currently looks like this:
TResult RunCommand<TResult>(Command<TResult> command, /* and some additional optional parameters */)
And since the C# driver heavily relies on implicit type conversions, there also is one from a string (and a BsonDocument) to the corresponding sub types of Command<TResult> (JsonCommand<TResult> and BsonDocumentCommand<TResult>). So you can effectively pass a string to the above new RunCommand() method, too.
You can therefore write either one of the following lines both of which do the exact same thing:
RunCommand<BsonDocument>("{count: \"collection_name\"}")
RunCommand<BsonDocument>(new BsonDocument("count", "collection_name"))

StringExpansion in c# called from Powershell

I have a small c# class, that does some logging stuff and that is called from a powershell scripting framework using:
[System.Reflection.Assembly]::LoadFrom("$ExtensionsPath\LogWriter.dll")
$Log = New-Object LogWriter($LogFile, $addTimeStamp, $logLevel, $overWrite)
Writing into the log file goes like this
$Log.AddInfo("myText")
Works fine so far.
What I am thinking about for some time is, if I am able to use stringexpansion in the AddInfo() method of my LogWriter class?
Look at the example:
$ModulesPath = ‘C:\temp\modules’
$test = ‘This is a text and I want to expand $ModulesPath in my c# LogWriter class’
$Log.AddInfo($test)
The c# class shall now expand the $modulespath in $test as powershell does. I already know that in c# I have access to the powershell runspace from which the c# class was called using System.Management.Automation Namespace. But then I am lost how to really expand the variable.
The entry written into the logfile should look like this:
This is a text and I want to expand C:\temp\modules in my c# LogWriter class
Of course I know I can do this in my script using
$Log.AddInfo(($ExecutionContext.InvokeCommand.ExpandString($test)))
But this is nasty because it looks ugly and if I forget to add this statement no expansion is done.
So I thought of retrieving the current Runspace in my c# class and do the ExpandString-Command there to get the expanded variable but I fail.
This is beyond my knowledge.
Anyone here to tell my if this is possible? I already think of some other tasks where to use this so please do not start a flame war about if this makes sense or not.
Rgds
Jan
How can the value for $ModulesPath be known outside of your script?
If you want it to be expanded in C#, then you have to send it, may be as a second Parameter to AddInfo like:
$Log.AddInfo($test, $ModulesPath)
Now it's known and the replacement could be done by:
string sNew = sTest.Replace("$ModulesPath", sModulesPath);
where sTest and sModulesPath are the parameters.
not sure if this is what you're asking about, but please try using double quotes on the $test string:
$test = "This is a text and I want to expand $ModulesPath in my c# LogWriter class"

Passing a COM object from C# to Perl using PerlNET

I’m trying to pass a COM object from C# code to Perl.
At the moment I’m wrapping my Perl code with PerlNET (PDK 9.4; ActiveState) and I have defined a simple subroutine (+ required pod declaration) in Perl to pass objects from C# to the wrapped Perl module.
It seems that the objects I pass are not recognized correctly as COM objects.
An example:
In C# (.NET 4.0), the ScriptControl is used to load a simple class from a file written in VBScript.
var host = new ScriptControl();
host.Language = "VBScript";
var text = File.ReadAllText("TestScript.vbs");
host.AddCode(text);
dynamic obj = host.Run("GetTestClass");
What I get (obj) is of type System.__ComObject. When I pass it to my Perl/PerlNET assembly and try to call method Xyz() in Perl I get the following (runtime) exception:
Can't locate public method Xyz() for System.__ComObject
If, however, I do more or less the same thing in Perl, it works. (In the following case, passing only the contents of my .vbs file as parameter.)
I can even use the script control :
sub UseScriptControl {
my ($self, $text) = #_;
my $script = Win32::OLE->new('ScriptControl');
$script->{Language} = 'VBScript';
$script->AddCode($text);
my $obj = $script->Run('GetTestClass');
$obj->Xyz();
}
Now, calling Xyz() on obj works fine (using Win32::OLE).
In both cases I use:
use strict;
use Win32;
use Win32::OLE::Variant;
Another approach:
I can invoke methods by using InvokeMember of class System.Type if I specify exactly which overload I want to use and which types I’m passing:
use PerlNET qw(typeof);
typeof($obj)->InvokeMember("Xyz",
PerlNET::enum("System.Reflection.BindingFlags.InvokeMethod"),
PerlNET::null("System.Reflection.Binder"),
$obj,
"System.Object[]"->new());
Using this approach would mean rewriting the whole wrapped Perl module. And using this syntax..
Now I am wondering if I am losing both the advantages of the dynamic keyword in .NET 4.0 and the dynamic characteristics of Perl (with Win32::OLE) by using PerlNET with COM objects.
It seems like my preferred solution boils down to some way of mimicking the behaviour of the dynamic keyword in C#/.NET 4.0.
Or, better, finding some way of converting the passed COM object to something that will be recognized as compatible with Win32::OLE. Maybe extract some information of the __ComObject for it to be identified correctly as COM object.
I have to add that I posted to the PDK discussion site too (but didn’t get any response yet): http://community.activestate.com/node/18247
I also posted it to PerlMonks - as I'm not quite sure if this is more a Perl or C#/.NET question:
http://www.perlmonks.org/?node_id=1146244
I would greatly appreciate any help - or advise on where to look further.

Passing Arbitrary Arguments From C# to Lua Functions

I have discovered the cause of the issue. An answer has been posted below.
EDIT: The problem has changed, please see "The problem" section.
I am using LuaInterface. The generic call for lua functions using this library has this signature LuaFunction.Call(params object[] args). I have created a wrapper function that catches exceptions from the library and formats them for display on the in-game console window.
I am trying to call a lua function, but it is not receiving the arguments. This is the line in C#
Game.Instance.scriptEngine.Call("GenerateChunk", chunks[chunkID], GetChunkGridPosition(chunkID));
Which is simply wrapping a call to this Lua function that accepts two arguments:
//lua
function GenerateChunk(worldChunk, chunkGridPosition)
Log(LogLevel.Error, worldChunk.ToString());
Log(LogLevel.Error, chunkGridPosition.ToString());
end
that merely calls back into a C# Log function (which resolves correctly, and is visible in the Lua context).
The problem is that I am getting an "invalid arguments to method call" error from luainterface when attempting to call the GenerateChunk function, throwing this back:
invalid arguments to method call
at JASG.ScriptEngine.LuaError(Exception ex) Scripting\ScriptEngine.cs:line 144
at JASG.ScriptEngine.Call(String fnName, Object[] args) Scripting\ScriptEngine.cs:line 86
at JASG.ChunkManager.WakeChunk(Int32 chunkID) World\ChunkManager.cs:line 123
at JASG.ChunkManager.GetChunk(Int32 chunkID, Boolean wakeIfAsleep) World\ChunkManager.cs:line 53
I have tried various ways of calling the ScriptEngine.Call method, tried wrapping the arguments in an object[] array, etc., but no dice. Any ideas why lua is not receiving my arguments that I am passing? I have verified both arguments are non-null in C# when being passed in.
I've never used Lua before, but I've seen this kind of strange behaviors with calling COM objects (or any interop), or when the target assembly call is loaded on a different App Domain, or any other technology that intercommunicates a .Net assembly with a non-.Net one.
Have you tried using the [Serializable] attribute on the classes that define the result of "chunks[chunkID]" and "GetChunkGridPosition(chunkID)"? Are all your interop classes and types compatible between both assemblies?
Just thinking out loud here.
Side note: you should reduce your code to the shortest example that produces the problem. For instance, we don't need to see your wrapper function. You should have tried removing it. If that solved the problem, it's an important clue you should have been mentioned. If the problem remained, then that code is just a distracting irrelevancy for anyone reading this.
Your problem could be in your Log function. Everything thing else looks fine, that's the only code we can't actually see, and your problem can be reproduced like this:
public static void Log(int errorLevel, string message)
{
Console.WriteLine(message);
}
public void Test()
{
var lua = new Lua();
lua.RegisterFunction("Log", this, GetType().GetMethod("Log"));
lua.DoString("function foo() Log('a','b') end");
lua.GetFunction("foo").Call();
}
In this case, because 'a' cannot be marshaled into a number.
I incorrectly identified the problem as being with the call into Lua. The error message I was receiving was in fact originating from the Lua script calling back into my C# Log function.
I have discovered the hard way that in spite of exposing the enum LogManager.LogLevel to the lua script envronment, Lua does not support enum types. Thus,
Log(LogLevel.Debug, "hello");
was becoming
Log("Debug", "hello");
when marshalled by LuaInterface for the C# function. It was not until I created an ancillary ScriptLog(string level, string msg) that I was able to properly use the function from within lua. I wanted to keep the functionality of being able to use the enum names within Lua.
NOTE: As Lua does not support enum types, tonumber(LogLevel.Debug) fails as well.

Can we pass directory or hashtable object as command line argument to VBscript?

I want to to pass directory or hashtable object as command line argument to vbscript. i am executing VBscript in c# application by using Process.Start() method.By using
Process.StartInfo.Arguments we can pass arguments to script, but this takes only string input.
Anybody know how to pass data other than string ?
Vbscript doesn't have hashes, the only thing that comes near are dictionary objects but that is not the same. Since you don't know which scripts you want to execute you have to assert the least common deminator and that is string type. So let all your scripts pass the arguments in string to your C function and in this function parse the arguments to the right type to use it in Process.Start

Categories