I'm trying to build a web form that asks for parameters, then when submit is clicked, it runs a PowerShell script with the parameters provided. I'm getting stumped on calling the ps1
file. I am using Visual Studio and whenever I try to run the project in a browser, the ps1 file is never ran and I can't seem to find any errors anywhere.
Here is my C#
code;
namespace MDTDatabase
{
using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ExecuteInputClick(object sender, EventArgs e)
{
AddResult.Text = string.Empty;
using (var shell = PowerShell.Create(InitialSessionState.CreateDefault2()))
{
Command commandfile = new Command("C:\\Scripts\\New-MDTComputer.ps1");
PSCommand pSCommand = shell.Commands.AddCommand(commandfile);
shell.Commands.AddParameter("serialnumber", SerialNumber.Text);
shell.Commands.AddParameter("purchasedate", PurchaseDate.Text);
shell.Commands.AddParameter("assetnumber", AssetNumber.Text);
shell.Commands.AddParameter("computerdescription", ComputerDescription.Text);
try
{
var Addresult = shell.Invoke();
}
catch (ActionPreferenceStopException Error) { AddResult.Text = Error.Message; }
catch (RuntimeException Error) { AddResult.Text = Error.Message; }
}
;
}
}
}
Right now my ps1
file only has "Write-Host hello" in it so I can easily verify that the script is running. Needless to say I get nothing in return.
I used this guide in creating the form so far. https://www.itdroplets.com/create-a-powershell-web-application/
I'm sure I'm doing something wrong with calling the ps1
, but can't seem to find the right search terms for Google or stackoverflow. Can someone help point me in the right direction?
I suggest much simplier syntax. Here's test script that I used:
Param($param);
set-content 'C:\users\user\Desktop\testFile.txt' $param;
and I invoke it in C# like:
System.Diagnostics.Process.Start("powershell.exe", @". 'C:\users\user\desktop\tst.ps1' -param 'some content'")
UPDATE:
Having the same PowerShell script as above, I managed to get it working with your code, ie:
using (var shell = PowerShell.Create(InitialSessionState.CreateDefault2()))
{
Command commandfile = new Command("C:\\users\\user\\desktop\\test.ps1");
PSCommand pSCommand = shell.Commands.AddCommand(commandfile);
shell.Commands.AddParameter("param", "some text");
try
{
var Addresult = shell.Invoke();
}
catch(Exception ex)
{
}
}
So, I guess, problem lies in your PowerShell script (my guess is lack of Param($param1, $param2, ...)
statement).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.