Passing an associative array from c# to Powershell - c#

I'd like to pass an associative array from C# to Powershell. As an example I'd like to execute this powershell line of code:
PS C:\> get-command | select name, #{N="Foo";E={"Bar"}} -first 3
Name Foo
---- ---
Add-Content Bar
Add-History Bar
Add-Member Bar
I'd like to do this via a Pipeline of distinct Commands as opposed to a single command marked as a script. Here's the code:
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.Add("get-command");
Command c = new Command("select-object");
List properties = new List();
properties.Add("name");
properties.Add("#{N=\"Foo\";E={\"Bar\"}}");
c.Parameters.Add("Property", properties.ToArray());
c.Parameters.Add("First", 3);
pipeline.Commands.Add(c);
pipeline.Commands.Add("Out-String");
Collection retval = pipeline.Invoke();
runspace.Close();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in retval)
Console.WriteLine(obj.ToString());
But that associative array being passed in as a parameter to Select-Object isn't being parsed correctly. This is what comes out the other side:
PS C:\test> c:\test\Bin\Debug\test.exe
Name #{N="Foo";E={"Bar"}}
---- --------------------
Add-Content
Add-History
Add-Member
What's wrong with how I'm setting up the Select-Object command parameters?

Creating a pipeline through c# and creating a pipeline with native powershell script have one major difference that is actually quite subtle: the parameter binder.
if I write a version of your code in pure script, I will get the same error: the hashtable literal is treated as a string value.
ps> $ps = $ps.Commands.Add("get-process")
ps> $ps = $ps.Commands.Add("select-object")
ps> $ps.Commands[1].Parameters.Add("Property", #("Name", '#{N="Foo";E={"Bar"}}'))
In this case, the command receives an array of two strings, the "name" and the hashtable literal string. This will be broken in exactly the same way as your C#. Now, take a look at the right way to do it (in script) - let me rewrite line 3:
ps> $ps.Commands[1].Parameters.Add("Property", #("Name", #{N="Foo";E={"Bar"}}))
So what changed? I removed the quotes around the hashtable -- I am passing a hashtable as the 2nd element of the object array! So, to get your C# example to work, you need to do what the parameter binder does for us at the command line (which is quite a lot!). Replace:
properties.Add("#{N=\"Foo\";E={\"Bar\"}}");
with
properties.Add(
new Hashtable {
{"N", "Foo"},
{"E", System.Mananagement.Automation.ScriptBlock.Create("\"Foo\"")}
}
);
I hope this clears it up for you. The parameter binder is probably the least visible but most powerful part of the powershell experience.
-Oisin

Related

C# pass parameter to power shell script file throws error

C# code has to pass parameter value to powershell script file. The code is working fine if I m not paasing any parameter. When I use .AddParameter or AddArgument it throws error.
while using AddArgument it throws error as 'A positional parameter cannot be found that accepts argument 'Test 111'.'
while using AddParameter I am getting erro as : 'A parameter cannot be found that matches parameter name 'FilePrefix'.'
Please find my C# code below
using (PowerShell ps = PowerShell.Create())
{
var scriptfile = #"\\cbc0056\work\Powershell\Scenarios\Test.ps1";
ps.AddCommand("Set-ExecutionPolicy")
.AddParameter("ExecutionPolicy", "RemoteSigned")
.AddParameter("Scope", "Process")
.AddParameter("Force");
ps.AddScript(scriptfile).AddCommand("Out-String");
//ps.AddArgument("Test 222");
ps.AddParameter("FilePrefix", "Test 222");
Collection<PSObject> results = ps.Invoke();
foreach (PSObject item in results)
{
_logger.LogInformation("Power Shell returned Values as given below " + "\r\n"+item.BaseObject.ToString());
// write some business logic
}
PowerShelll script Test.ps1 file as given below
Param(
[Parameter(Position=1)]
[string]$FilePrefix
)
$test = $FilePrefix
Write-Host "hello this is a test " | Out-String
Write-Host $test| Out-String
$test
Get-Process | Out-String
What is wrong in passing parameter ? Any help would be highly appreciated.
Use .AddCommand() to execute a script file (.ps1); only use .AddScript() to execute a script block, i.e. a piece of PowerShell code.
As Mathias notes, your .AddParameter() call must come before adding another pipeline segement with .AddCommand("Out-String").
ps.AddCommand(scriptfile).AddParameter("FilePrefix", "Test 222").AddCommand("Out-String");
Also note that there's an easier way to set the execution policy, via an object specifying the initial session state: see this answer.

How to catch full invoke text from powershell class in C#

I want to catch the output exactly as I get it when I run commands in PowerShell.
For instance when I type LS, I get:
Yet when I use this code:
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
PowerShell ps = PowerShell.Create(); // Create a new PowerShell instance
ps.Runspace = runspace; // Add the instance to the runspace
ps.Commands.AddScript("ls"); // Add a script
Collection<PSObject> results = ps.Invoke();
runspace.Close();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
Console.WriteLine(obj.ToString());
}
I get the following output:
Microsoft.Management.Infrastructure.dll
System.Management.Automation.dll
System.Management.Automation.xml
WpfApp1.exe
WpfApp1.exe.config
WpfApp1.pdb
Although this output may come in handy, with an other application I dont get the right output in return, so I would prefer the exact output as I see it in PowerShell itself.
Is there a way to read the output as I get it in PowerShell, line for line?
If you want the exact text that powershell produces you then you can use Out-String in the powershell command:
ps.Commands.AddScript("ls | Out-String");
You can also read the values by accessing the Properties of the PSObject:
foreach (PSObject obj in results)
{
var name = obj.Properties["Name"]?.Value.ToString()
var mode = obj.Properties["Mode"]?.Value.ToString();
var length = obj.Properties["Length"]?.Value.ToString();
var lastMod = (DateTime?)obj.Properties["LastWriteTime"]?.Value;
Console.WriteLine(string.Format("{0} {1} {2} {3}", mode, lastMod, length, name));
}
Note, as mentioned in mklement0's answer, you don't need to use Runspace to execute this powershell. Consider using Get-ChildItem rather than ls.
Note: This answer also recommends what part of haldo's helpful answer shows, in a more focused manner and with supplementary information.
Modify your script to pipe your command to the Out-String
cmdlet, which uses PowerShell's formatting system to render to a string, the same way that output renders to the console.
ps.AddScript("ls | Out-String"); // Add a script
Note:
Windows PowerShell assumes a fixed line width of 120 characters and with (implied) tabular (Format-Table) or wide (Format-Wide) formatting, truncates lines that are longer (except if the output object is of type [string]), with the point of truncation indicated with ...
PowerShell [Core] 7+ exhibits the same behavior fundamentally, but only uses default width 120 as a fallback: when the hosting (console-subsystem) executable is running in a console (terminal), the console window's width is used instead, which is the same behavior you get in a regular PowerShell console window (see this answer).
To fix that, pass a large-enough line width to -Width; e.g.:
ps.AddScript("ls | Out-String -Width 200");
Note:
In Windows PowerShell, do not use -Width ([int]::MaxValue-1), because every line is then padded to that width, which will result in excessively large output.
PowerShell [Core] 7+, this padding is no longer performed, and you can safely use
-Width ([int]::MaxValue-1)
A few asides:
For robustness, I suggest avoiding the use of aliases (such as ls for Get-ChildItem) in scripts and compiled code.
In the case at hand, ls wouldn't work on Unix-like platforms, because the alias isn't defined there, so as not to conflict with the platform-native ls utility.
It's best to wrap PowerShell ps = PowerShell.Create(); in a using block to ensure that the PowerShell instance is disposed of: using (PowerShell ps = PowerShell.Create()) { ... }
There is generally no need to create a runspace explicitly - PowerShell.Create() will create one for you.
The System.Management.Automation.PowerShell instance returned by PowerShell.Create() directly exposes methods such as .AddScript() - no need to use the .Commands property.
You can get compressed json output from powershell with this command
ls | ConvertTo-Json -Compress
Then deserialize. Also this command provide extra info than see in powershell output.

Retrieving GetExecutingRequests from PowerShell into c# object

I am trying to retrieve data from PowerShell into a c# object. The data I am looking for is returned from a PowerShell Invoke() of GetExecutingRequests on a remote web server. The issue I'm having is that I am not getting an error code, but the results from the Invoke() that I'm looking for are nowhere in the return data, or on the PowerShell object.
using (Runspace runspace = RunspaceFactory.CreateRunspace(cxn))
{
runspace.Open();
using (PowerShell ps = PowerShell.Create())
{
ps.Runspace = runspace;
string script = String.Format("Get-WmiObject
WorkerProcess -Namespace root\\WebAdministration -ComputerName {0} |
Invoke-WmiMethod -Name GetExecutingRequests", server);
ps.AddScript(script);
ps.AddParameter("OutputElement", new HttpRequest[0]);
var result = ps.Invoke();
}
}
This code executes, and returns a Collection with 29 items. However, none of them show the GetExecutingRequests results, and there is nothing relevant on the PowerShell object either.
I would like to get the output of GetExecutingRequests into a c# object, so I can do further processing. the PSDataStreams on the ps object also have no results.
Any help would be appreciated.
MORE INFO:
I was able to solve this with a change to the PowerShell script I was sending:
string script = String.Format("Get-WmiObject WorkerProcess -Namespace root\\WebAdministration -ComputerName {0} | Invoke-WmiMethod -Name GetExecutingRequests | %{{ $_ | Select-Object -ExpandProperty OutputElement }}", server);
I'm not quite sure if I can resolve the results directly, but I'd advise running below command to get some some more information on the object being returned. From there, you could look into how you'd handle that returning in C#.
Get-WmiObject -Class $(<scriptblock>) | get-member
Define the object types in C# & see if you're able to capture it in that way first.
If you're not able to make any progress with capturing the object type being returned in powershell yourself, it may be worth posting here to see if anyone else might be able to offer any insight/experience with workarounds for interfacing those objects types into C#.
If above really isn't possible, forcing the powershell to return everything from standard out would help find if it's writing anything meaningful that you can scrape/format in C#. I think the best way to do that in your quoted powershell command would be like so:
return $(Get-WmiObject
WorkerProcess -Namespace root\WebAdministration -ComputerName {0} |
Invoke-WmiMethod -Name GetExecutingRequests | *>&1)
This returns all 5+ standard outs from powershell to the return object (for those reading, see these docs on ps streams). Youshould definitely be able to capture the return in your results variable, but it can't hurt to make sure you're able to throw/capture errors from overflow.
Hope this helps to continue the digging!

C# powershell scripting

I know how to execute a single powershell command and view the results of it using C# code. But I want to know how to execute a set of related commands as below and get the output:
$x = some_commandlet
$x.isPaused()
Simply, I want to access the return value of $x.isPaused().
How do I add this functionality to my C# application?
For such commands, it is better that you create something called pipeline and feed it your script. I have found a good example of this. You can find further about this code and such projects here.
private string RunScript(string scriptText)
{
// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
// open it
runspace.Open();
// create a pipeline and feed it the script text
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
// add an extra command to transform the script
// output objects into nicely formatted strings
// remove this line to get the actual objects
// that the script returns. For example, the script
// "Get-Process" returns a collection
// of System.Diagnostics.Process instances.
pipeline.Commands.Add("Out-String");
// execute the script
Collection<psobject /> results = pipeline.Invoke();
// close the runspace
runspace.Close();
// convert the script result into a single string
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
return stringBuilder.ToString();
}
This method is neatly done with proper comments. Also you can directly go to the link of Code Project I gave download it and start playing!

take powershell object save as xml and load in c#

I have the following powershell script that scans a location and adds the file details to a xml file,
Get-ChildItem -recurse c:\DATA | Select-Object * , #{Name="Kbytes";Expression={ "{0:N0}" -f ($_.Length / 1Kb) }},#{Name="Age";Expression={ (((Get-Date) - $_.CreationTime).Days) }} | Export-Clixml c:\DATA\Final.xml
As far as I understand this should be a object in the .net framework, assuming a dataset ?
what I would like to do is load this object into a c# application and use it as a dataset.
How would I load the object into a dataset in c# ?
Add reference to the System.Management.Automation.dll assembly.
Create a PowerShell Runspace
Open the Runspace
Create a PowerShell Pipeline object with the Import-CliXml command
Invoke the Pipeline
Close the Runspace
var rs = RunspaceFactory.CreateRunspace();
rs.Open();
var pl = rs.CreatePipeline(#"Import-CliXml c:\DATA\Final.xml;");
var result = pl.Invoke();
rs.Close();
A faster approach might be:
-For lists
object[] xmlAsList =
System.Management.Automation.PSSerializer.DeserializeAsList(System.IO.File.ReadAllText(#"C:\Users\batman\Desktop\myList.clixml"));
-For generic objects
object importedObject =
System.Management.Automation.PSSerializer.Deserialize(System.IO.File.ReadAllText(#"C:\Users\batman\Desktop\myObject.clixml"));
Then, you manage the results via: System.Management.Automation.PSObject using the Members property.

Categories

Resources