I've done some work hosting PowerShell and have done a lot of reading but I am seeing strange behavior and it makes me wonder if I do not understand the host like I thought I did.
I am creating a Runspace with RunspaceFactory:
var runSpace = RunspaceFactory.CreateRunspace()
I'm utilizing the same runspace throughout the execution of my host. When I first start the host I invoke a Import-Module command:
var pipeline = runSpace.CreatePipeline();
var psCommand = new Command("Import-Module");
psCommand.开发者_开发问答Parameters.Add("Name", directory + "MyModule");
pipeline.Commands.Add(psCommand);
pipeline.Invoke();
"directory" is a directory that is not the default module directory. I can use the same import-module command with the exact same syntax in a PowerShell command window and it works fine. The command appears to complete successfully within my custom host. Later in the execution I attempt to call a cmdlet within the module:
var pipeline = runSpace.CreatePipeline();
var psCommand = new Command("Get-Stuff");
pipeline.Commands.Add(psCommand);
var stuff = pipeline.Invoke();
But on invoke I get the exception that "Get-Stuff" is not a cmdlet..etc.
My understanding was the a Runspace would maintain this type of state. Is this not the case? I have created a host successfully within another project. The two main differences are that that host is utilizing the default module directory (Documents\Modules\) and I call the CreateRunspace() method like this:
var runspace = Runspace.CreateRunspace(customHost);
Do I have to define a PSHost to be able to maintain state?
This was actually an issue with the directory of the module having a trailing "\".
Import-Module -Name "D:\aaa\Modules\Xyd\" is invalid.
精彩评论