Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to pass arguments to Powershell script from C#

2,228 views
Skip to first unread message

Frank

unread,
Sep 9, 2008, 4:23:03 PM9/9/08
to
Hi,

I am write a C# webservice app which runs a Powershell script and it runs it
but I cannot seem to pass any arguments to it. Can someone help?

Thanks,

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;


namespace webservice_ilist
{
/// <summary>
/// Summary description for ilist
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET
AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class ilist : System.Web.Services.WebService
{

[WebMethod]
public string[] return_array(string scriptname, string args)
{

IList<string> list = new List<string>();

Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
Command cmd = new Command(scriptname);
cmd.Parameters.Add(args);
pipeline.Commands.Add(cmd);

Collection<PSObject> results;
results = pipeline.Invoke();

foreach (PSObject obj in results)
{
list.Add(obj.ToString());
}

// return test;

return list.ToArray();
}
}
}

Frank

unread,
Sep 9, 2008, 4:39:01 PM9/9/08
to
Nevermind, I got it to work with:

Command cmd = new Command(scriptname + " " + args,true);

Thanks,

Justin

unread,
Sep 17, 2008, 1:59:00 AM9/17/08
to

Nice one Frank - I've been looking for a solution to passing params
(including both PS arguments, and filter criteria) through to pikeline and
you hit the nail on the head. Here's an example using both command-line args
and filter criteria:

Dim cmdPS As Command = New Command("D:\NTAPPS\WebAppAce\GetConnsAce.ps1" + "
" + sACE + " | where {$_.State -match 'ESTAB'}", True)
MyPipeline.Commands.Add(cmdPS)
Dim results As Collection(Of PSObject) = MyPipeline.Invoke()

Thanks again ...

Frank

unread,
Sep 17, 2008, 11:31:02 AM9/17/08
to
NP :-)
0 new messages