Reputation: 4244
I have a Powershell script that I want to run on my server triggered from within an ASP.NET MVC application. I'm currently doing so like this:
var shell = PowerShell.Create();
shell.Commands.AddScript(_script);
_output = new PSDataCollection<PSObject>();
var input = new PSDataCollection<string>();
input.Complete();
shell.BeginInvoke(input, _output);
However the script is running under the same user account as the IIS application (obviously). This account doesn't have the required priviledges the script needs to do it's work. I've tried adding an intermediate script and using Invoke-Command with the credentials of an authorised account to run the main script, but the Invoke-Command never fires when run from the ASP.NET process, and doesn't return an error.
For example, take the following script:
"Start"
Invoke-Command -computername WinServer -Credential $credentials -ScriptBlock
{
"Test"
}
"Finish"
When I run this from PS on the server, I get the response "Start, Test, Finish", but when I run it from ASP.NET it simply returns "Start, Finish" - the script block never runs.
Is there either an explanation for why the script block isn't running, or a way within System.Management.Automation.Powershell to elevate to admin or specify a user account to run it as?
Upvotes: 0
Views: 2160
Reputation:
So, what's most likely happening, is that the Invoke-Command
call is throwing an exception. My best guess is that it's throwing an exception due to an authentication issue of sorts.
For a little background, PowerShell has multiple "streams". You're probably only seeing the data emitted to the Output
stream, so what we need to do is capture the other streams, and merge them into the Output stream, so we can inspect any warnings, errors, or other information.
There are a few different ways that you can "capture" the errors, and inspect them:
Wait-Debugger
command into the script (Requires PowerShell 5.0), and then attach to the process remotely using Enter-PSHostProcess
-ErrorVariable
parameter on the Invoke-Command
to capture the errors and then write them to a file, or to the output stream (use Write-Output
)*>&1
Practically speaking, I'd update your script code to look like this:
"Start"
Invoke-Command -computername WinServer -Credential $credentials -ScriptBlock {
"Test"
} -Verbose *>&1
"Finish"
That should cause all errors, warnings, verbose output, etc. to be merged into the output stream, so you should be able to see what's going on inside the script.
Upvotes: 1