Powershell call from C # (ASP.NET) - pass custom object?

I am having trouble trying to call a Powershell function with C #. In particular, I'm stuck trying to pass a generic Project list to a powershell module function. Here is the code:

var script = @". \\server01\Modules\Runspace.ps1; Get-MyCommand"; var allProjects = _pmRepository.GetAllProjects(); using (Runspace runSpace = RunspaceFactory.CreateRunspace()) { runSpace.Open(); PowerShell posh = PowerShell.Create(); posh.Runspace = runSpace; posh.AddScript(script); posh.AddArgument(allProjects); Collection<PSObject> results = posh.Invoke(); } 

The GetAllProjects () method returns a common list of Project and Project is a custom class. My module function signature is as follows:

 function Get-MyCommand { [CmdletBinding()] Param ( [Parameter(ValueFromPipeline = $true)] [PSCustomObject[]] $Projects ) Begin {} Process { $consumables = New-GenericList "Company.Project.Entities.Project" foreach($project in $projects) { if ($project.State -eq $ProjectStates.Development) { $consumables.Add($project) } } } } 

I get this error when I try to iterate over an array:

{"Property" State "could not be found on this object. Make sure it exists." }

Can I do what I'm trying to do?

Edit: For some time I used the code below, but ended up using C # code for this web application. The loading time for creating a powershell session was too long for our situation. Hope this helps.

  private void LoadConsumableProjects() { var results = new Collection<PSObject>(); InitialSessionState iss = InitialSessionState.CreateDefault(); iss.ImportPSModule(_modules); using (Runspace runSpace = RunspaceFactory.CreateRunspace(iss)) { runSpace.Open(); using (var ps = PowerShell.Create()) { ps.Runspace = runSpace; ps.AddScript("Get-LatestConsumableProjects $args[0]"); ps.AddArgument(Repository.GetAllProjects().ToArray()); results = ps.Invoke(); if (ps.Streams.Error.Count > 0) { var errors = "Errors"; } } } _projects = new List<Project>(); foreach (var psObj in results) { _projects.Add((Project)psObj.BaseObject); } } 
0
source share
1 answer

Ok, I said that is the answer, because I think you can check it out. Since I understand your code, you are passing an argument to your script:

 posh.AddArgument(allProjects); 

But inside your script, you are not using this argument to jump to your function. For me you can check:

 var script = @". \\server01\Modules\Runspace.ps1; Get-MyCommand $args[0]"; 

In your script, you will get the source "Runspace.ps1", and then call the Get-MyCommand function without parameters. PowerShell falls into the foreach loop with $ project null. Just beep if $ Projects is null.

+1
source

All Articles