My PS script returns a string.
Function GetData {
Param(
[string]$id
)
Process
{
return "Value is $id"
}
GetData -id $arg
The below is the C# that calls the PS script:
PowerShell ps = PowerShell.Create();
string psScript = "GetData.ps1";
ps.AddScript(psScript);
// only takes one parameter
ps.AddParameter("25");
Collection<PSObject> results = ps.Invoke();
foreach (PSObject r in results)
{
Console.WriteLine(r.ToString());
}
Console.ReadLine();
Nothing returns.
I double checked the script and it does return a value when I pass in the path manually when calling the script directly in PowerShell. I also made sure that in the Properties of the project the Platform target is x64 (based on another question's error). I also tried to directly save the result in the Invoke method, but it gave an error, which showed that I have to actually save it in a collection, even though it's one record.
Forgot, also tried:
psParam = "25";
string psScript = "GetData.ps1 -arg'" + psParam + "'";
And no result on the console.
Tested this:
PowerShell ps = PowerShell.Create();
string psScript = ".\\GetData.ps1";
ps.AddCommand(psScript);
ps.AddArgument("25");
Collection<PSObject> results = ps.Invoke();
foreach (PSObject r in results)
{
Console.WriteLine(r.ToString());
}
Console.ReadLine();
And used most of the above and this errors because it says GetData.ps1 is not recognized as the name of a cmdlet, function, script file, or operable program. If I point directly to it by placing it on my C drive (C:\GetData.ps1), it does nothing.
Double check; inside the script I am calling the function on the last line:
GetData -id $arg
Is this correct?
Pay attention to your function. It gets an open curly brace '{', but not the matching close curly brace '}'. Your defective PowerShell code will emit an error not caught by your code.
After you correct this simple error, notice how you're calling your function. What is $arg? I assure you it's not any automatic variable. Have a look in about_automatic_variables...
P.S.: you'd better off asking enormously difficult questions like this one in social . technet . microsoft . com / Forums / windowsserver / en-US / home?forum=winserverpowershell . If you ha did it, the answer would have been posted many hours ago.
The problem is that "return" is not what you think.
In Powershell, the "return value" is the last value on the stack when execution ends. In your case, just omit the "return" keyword, and the string will come out as you expect.
Function return value in PowerShell
Alternatively, you can use Write-Output which would explicitly send the data to the output like a C-style return statement.
Note: Do NOT use Write-Host, as it writes directly to the powershell host, skipping the pipeline and never giving you a chance to see the value.
Related
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.
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.
I need to convert PSObject to String(). Is there any standard way available to do this task? Somehow powershell also does ToString() or spits out a readable stream on ISE console.
I used PSSerializer.Serialize(PSObject) but it serializes everything. I want in my application seemlessly everything shown in a way the way Powershell does.
Is there anyway to convert PSObject to a.readable string. At the moment when I use following line of code
PSObject.ToString()
or
PSObject.BaseObject.ToString()
both just print out complete type name. ( e.g. "System.Collection.HashTable" )
But I want complete displayed contents to see the way powershell exposes.C#
You could get PowerShell to format it for you.
foreach (PSObject obj in myPsObjects)
{
var formattedObj =
System.Management.Automation.PowerShell
.Create()
.AddCommand("Write-Output").AddArgument(obj)
.AddCommand("Out-String")
.Invoke();
string message = string.Join(" ", formattedObj);
Console.Write(message);
}
I have a C# function which actually invokes a powershell asynchronously
Below is my code:
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript(scriptFile,false);
PowerShellInstance.AddParameter("var", "Value");
PSDataCollection <PSObject> outputCollection = new PSDataCollection<PSObject>();
IAsyncResult result = PowerShellInstance.BeginInvoke<PSObject, PSObject>(null, outputCollection);
while (result.IsCompleted == false)
{
foreach (PSObject outputItem in outputCollection)
{
System.Console.WriteLine(outputItem.BaseObject.ToString());
}
System.Console.WriteLine("Waiting for pipeline to finish...");
Thread.Sleep(1000);
}
}
while this works like i nee to to , the addition of the parameter doesn't seem to do any thing. I have made that parameter compulsory in powershell , no success nothing happens then. If its not compulsory it just works and doesn't process the parameter.
My Powershell is:
Param(
[Parameter(Mandatory=$False,Position=1)]
[string]$var
)
. "C:\Data\initiate.PS1"
write-output "Value is $var"
The output is:
In Initiation -- This is coming from the PS initation script
Value is
Waiting for pipeline to finish...
IF I make the parameter Required as true in Powershell the output is:
Waiting for pipeline to finish...
I have tried changing he scope in the PowerShellInstance.AddScript, no use.
This might look like a duplicate question but I couldn't find the solution hence asking here.
The msdn link i used to create this code is at:
https://blogs.msdn.microsoft.com/kebab/2014/04/28/executing-powershell-scripts-from-c/
Any help is really appreciated.
Please add/mark PetSerAl's comment as answer, worked for me. Thank you
AddScript -> AddCommand
I have a variable in my psm1 file that's a KVP hash
$subcmdlist = #{
"addhost" = "Add-Host";
"deletehost" = "Remove-Host";
"setparameter" = "Set-Parameter";
}
This psm1 file also has a function called 'newtask' which accepts an argument of $subcommand.
I'm wondering how i can execute the cmdlet Add-Host when
newtask addhost
is issued from the shell.
I tried to just echo it but that didn't do much good at all. Just printed out the value.
Thanks!
Use the & sign (aka the call operator), like this: & "Get-Host". This works at least in Powershell 3.0.