I have been trying out running a PowerShell script from asp.net with no success for a few days already.
The C# is:
using (var process = new Process())
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = @"powershell.exe";
startInfo.Arguments = "arguments that call the script here";
startInfo.RedirectStandardOutput = false;
startInfo.RedirectStandardError = false;
startInfo.UseShellExecute = true;
startInfo.CreateNoWindow = true;
process.StartInfo = startInfo;
process.Start();
}
The PowerShell script it calls contains the ff:
robocopy "\\network-server\location" "C:\localfolder" "testmovefile.txt"
Obviously the problem here would be the proper credentials. But I have tried doing all sorts of impersonation stuff, whether from C# or in the script level. I tried doing this to the PowerShell script:
$username = "domain\user"
$password = ConvertTo-SecureString –String "password" –AsPlainText -Force
$pp = new-object -typename System.Management.Automation.PSCredential -argumentlist $username,$password
start-process powershell -argument "C:\localfolder\CopyFile.ps1" -Credential $pp
It works when I run the script in the PowerShell console locally, even when using an account that has no permissions to the network, however when called from the web app.. nothing happens.
The App Pool Identity is just set to the default App Pool Identity though.. I found out that if I change the identity to a custom account with the proper rights.. it works.
I am still trying to search for a different solution.. I want a scenario that you can just change anything in the script and it will still still run. Any is OK as long as it does not change the app pool identity.
I tried these as well:
- http://huddledmasses.org/using-alternate-credentials-with-the-filesystem-in-powershell/
- using runspace in c# instead of process and using an impersonator How do you impersonate an Active Directory user in Powershell?
But it still doesn't work. I keep on getting access denied. Question is, is it possible to make it work by impersonating someone inside PowerShell?