0

I've created a PowerShell function (called Get-FileInUse) that will parse our data server for a list of known files. The function returns ($global:result as array) which files are in use and by whom.

I'd like to host an internal website that shows (when accessing it or when pressing a button on the site) the output of this function. Say an internal website inusefiles.corp.com. Don't bother about bindings and DNS records, I'll manage that.

I've followed a tutorial online (this one), but it's hard to understand what's going on.

These are my two questions:

  1. How do I add my script in the aspx.cs file? I would like to have the script run when loading the page. Placing it under protected void Page_Load(object sender, EventArgs e) seems logical to me.
  2. My function returns a variable $result. How do I show it in eg. a text box?

Note: I don't have any experience with ASP.NET/Web Forms. PowerShell is no problem for me.

IT M
  • 359
  • 1
  • 2
  • 12
  • 2
    This seems to be an exact copy of the question you posted yesterday and had closed due to it being too broad and that you then deleted. I noticed you commented on my answer that you were getting "compilation errors" but you never specified _which errors_. – Mathias R. Jessen Apr 16 '20 at 17:30
  • Hi Mathias, I kind of had no other choice... Error was: `Compiler Error Message: CS1056: Unexpected character '$'`. – IT M Apr 17 '20 at 08:00
  • In `Line 14: ps.AddScript($". {scriptPath}").AddStatement().AddScript("Get-FileInUse").AddCommand("Out-String");` – IT M Apr 17 '20 at 08:00
  • 2
    what version of C# are you using? The $ sign isn't valid [until C# 6](https://stackoverflow.com/questions/32878549/whats-with-the-dollar-sign-string). – ADyson Apr 17 '20 at 08:42
  • Sorry for the noobish question, but where can I check this? – IT M Apr 17 '20 at 11:02
  • Never mind, found it: `Microsoft (R) Visual C# Compiler version 4.8.3752.0` `for C# 5` – IT M Apr 17 '20 at 11:04

1 Answers1

1

Okay, found it:

Under protected void Page_Load(object sender, EventArgs e) came:

string scriptOutput = "";
using (var ps = System.Management.Automation.PowerShell.Create(System.Management.Automation.Runspaces.InitialSessionState.CreateDefault()))
{
    ps.AddStatement().AddScript("Get-FileInUse").AddCommand("Out-String");

    foreach (var res in ps.Invoke())
    {
        scriptOutput = string.Join(Environment.NewLine, scriptOutput, res);
    }
}
Result.Text = scriptOutput;

While my Default.aspx contains a ASP Textbox with ID="Result":

<asp:TextBox ID="Result" TextMode="MultiLine" Width="50%" Height="300" runat="server">
</asp:TextBox>
IT M
  • 359
  • 1
  • 2
  • 12