I am not getting any error below but I am also not getting the output. Below is the Powershell cmd and the C# method which is calling it. I would like to know if it is written correctly and how can I get the output as coming from powershell. It works fine when I run from PowerShell window
Pwsh cmd:
public class GetRowAndPartitionKeys : Cmdlet
{
[Parameter(Mandatory = false)]
public List<string> Properties { get; set; } = new List<string>();
}
[Cmdlet( VerbsCommon.Get, "RowAndPartitionKeys" )]
public class GetRowAndPartitionKeyCmd : GetRowAndPartitionKeys
{
protected override void ProcessRecord()
{
WriteObject ("Hi");
}
}
}
C# method:
public async Task<IEnumerable<object>> RunScript( )
{
// create a new hosted PowerShell instance using the default runspace.
// wrap in a using statement to ensure resources are cleaned up.
string scriptContents = "Import-Module 'C:\Users\...\Powershell.dll";
using( PowerShell ps = PowerShell.Create() )
{
// specify the script code to run.
ps.AddScript( scriptContents ).AddCommand( "Get-RowAndPartitionKeys" );
// execute the script and await the result.
var pipelineObjects = await ps.InvokeAsync().ConfigureAwait( false );
foreach( var item in pipelineObjects )
{
Console.WriteLine( item.BaseObject.ToString() );
}
return pipelineObjects;
}
Similar to the answer to your previous question, the following self-contained sample code demonstrates that the approach works in principle, after correcting the following problems in your code:
An
.AddStatement()
call is missing between the.AddScript()
and the.AddCommand()
call; this is necessary for the (script block-based)Import-Module
call and theGet-RowAndPartitionKeys
call to be treated as separate statements.Pseudo-code line
string scriptContents = "Import-Module 'C:\Users\...\Powershell.dll";
is missing a closing'
(possibly just an artifact of posting here).Also, troubleshooting code is added below.
While the orchestration code is in PowerShell, actual C# projects, compiled via the .NET SDK are used, in combination with version
7.1.2
of the PowerShell (Core) SDK package,Microsoft.PowerShell.SDK
.After running the code, which creates and runs the test projects, you can inspect and experiment with them yourself (
./module
is the project for the module DLL that defines theGet-RowAndPartitionKeys
cmdlet,./app
is the project for the application that calls it):On my Windows 10 machine (running from PowerShell 7.1.2), I get:
As you can see:
Hi
shows that the cmdlet was successfully called.