Run PS Script with arguments - c#

I'm trying to run powershell script from relative path (script is placed in project folder) with arguments.
This is what i tried:
public static void RunPSScriptWithArgumentsFromScriptsFolder(string NameOfScriptFile, string arguments)
{
string RelativePathToApp = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
Process proc = Process.Start("C:\\windows\\system32\\windowspowershell\\v1.0\\powershell.exe ", #"-noexit -File """+RelativePathToApp+"\\Scripts\"" +NameOfScriptFile +arguments);
proc.WaitForExit();
}
Problem is when i run it my powershell window just flash once and disseapers even with -noexit switch.
This is script which im trying to run for better reproducing problem:
https://community.spiceworks.com/scripts/show/4378-windows-10-decrapifier-18xx-19xx
Any ideas what could be wrong?
PS: My Set-ExecutionPolicy is set to Unrestricted

Related

Powershell script in C# for joining windows domain

I am using this function below to create powershell script
public static void joinDomain()
{
string path = #"C:\Windows\Temp\Test.ps1";
if(!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("add-computer –domainname ad.contoso.com -Credential AD\adminuser -restart –force");
}
}
}
After successfully script creation I run that script using this below code
Classes.Functions.joinDomain();
string strCmdText = #"C:\Windows\Temp\Test.ps1";
System.Diagnostics.Process.Start("C:\\windows\\system32\\windowspowershell\\v1.0\\powershell.exe ", strCmdText);
If i run script from Powershell ISE it prompts for password so the script works.
Even calling it works but i just got blue powershell commandline and then it disseaper it wont ask for password and i dont know why.
Any ideas would be appreciated?
Found solution:
It was cause by windows restricted policy for unsigned scripts.
Solution here:
https://github.com/eapowertools/ReactivateUsers/wiki/Changing-Execution-Signing-Policy-in-Powershell

PowerShell not targeting 4.6

I am trying to run a PowerShell script inside C# using .NET 4.6
I have tried to install the PowerShell NuGet but it doesn´t target .NET 4.6
Is there another way I could execute the PowerShell script?
I needed to specify powershell.exe to be able to run the script. But now I have another problem the PowerShell window closes immediately so I am not able to see the error message. I am using the following command
var s = Process.Start(#"Powershell.exe", $#"-noexit -ExecutionPolicy Bypass -file ""MyScript.ps1; MyFunction"" ""{arguments}""");
s.WaitForExit();
Yes, you can run it as you run any external program. System.Diagnostics.Process will help you out.
Here is a code example from Microsoft community:
using System.Diagnostics;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
Process myProcess = new Process();
myProcess.StartInfo.FileName = #"ConsoleApplication1.exe";
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.RedirectStandardOutput = true;
myProcess.StartInfo.RedirectStandardInput = true;
myProcess.Start();
string redirectedOutput=string.Empty;
while ((redirectedOutput += (char)myProcess.StandardOutput.Read()) != "Enter File Name:") ;
myProcess.StandardInput.WriteLine("passedFileName.txt");
myProcess.WaitForExit();
//verifying that the job was successfull or not?!
Process.Start("explorer.exe", "passedFileName.txt");
}
}
}
ConsoleApplication1.exe should be replaced with YourApplication.ps1
Why would you ever use System.Diagnostics.Process rather than System.Management.Automation which is recommended? Because powershell is slow and if you ever need to replace it, using System.Diagnostics.Process will allow doing it immediately.

File copy started from aspnet webforms and implemented using batch, pstools and robocopy doesn't work

I have 4 independent servers (not in domain):
IIS, SQL1, SQL2, SQL3
I want to copy a database backup from SQL1 to SQL2 or SQL3 (depending on parameters) by button click on webpage hosted on IIS
I wrote a button click method for that, which is calling batch file located in inetpub folder on IIS
Batch is using pstools to run robocopy on SQL1 which should copy required file to destination server (SQL2 or SQL3)
This solution works if I execute batch directly on IIS (cmd as Administrator) or when I debug it on my local machine, but it doesn't if it is called from the running site.
It even doesn't spend any time between the following lines:
batchProcess.Start();
batchProcess.WaitForExit();
Here is my copy method:
private bool ProcessCopy(string file, string destinationIp)
{
SecureString password = ConvertToSecureString("myPassword");
try
{
string batchPath = Server.MapPath(".") + "\\CopyFile.bat";
string cmd = #"c:\Windows\System32\cmd.exe";
ProcessStartInfo processInfo = new ProcessStartInfo
{
FileName = cmd,
UseShellExecute = false
};
Process batchProcess = new Process {StartInfo = processInfo};
batchProcess.StartInfo.Arguments = $"/C {batchPath} {file} {destinationIp}";
batchProcess.StartInfo.Domain = "";
batchProcess.StartInfo.UserName = "Administrator";
batchProcess.StartInfo.Password = password;
batchProcess.StartInfo.RedirectStandardOutput = true;
batchProcess.StartInfo.RedirectStandardError = true;
batchProcess.StartInfo.CreateNoWindow = true;
batchProcess.Start();
batchProcess.WaitForExit();
string response = batchProcess.StandardOutput.ReadToEnd();
response += batchProcess.StandardError.ReadToEnd();
statusStringAppend($"response: {response}");
return true;
}
catch (Exception ex)
{
statusStringAppend($"Failed: {ex.Message}. {ex.StackTrace}");
}
return false;
}
Batch body is:
#echo off
c:\qa\tools\pstools\psexec64.exe -accepteula -u Administrator -p myPassword \\SourceIP robocopy \\SourceIP\qa\db_backup\ \\%2\qa\db_backup\ %1 /is
My questions are:
1. Why the file was not copied?
2. Is there any better way to get it copied?
CODE UPDATED ACCORDING TO SUGGESTIONS BELOW
My guess is that you never executed pstools as the user that your IIS service is running as before, so the EULA dialog is blocking your execution.
If you remember, you always got a window and needed to press the accept button when running any sysinternals tool like pstools the first time.
I guess this should work for you:
c:\qa\tools\pstools\psexec64.exe -accepteula -u Administrator -p myPassword \\SourceIP robocopy \\SourceIP\qa\db_backup\ \\%2\qa\db_backup\ %1 /is
[EDIT]
You would most likely have hit this problem later on, anyway it did not work for you, so i have to list what else could be wrong with your code:
starting a .bat file needs cmd.exe as mother process, you cannot just start a .bat file as process directly. Instead you can for example use another method than ProcessStartInfo that spawns the system default script interpreter automatically: Executing Batch File in C#
the process for executing batch files is "cmd.exe", first parameter "/C", second parameter the batch file you are executing
when executing typical commandline tools, you might consider reading the SDTOUT (standard output) of the process you are executing, like this: Capturing console output from a .NET application (C#)

How to view Process.Start() Arguments as they are passed to executable

I'm trying to run a fortran executable with Process.Start and it is not working.
Process proc = new Process();
string args = "<C:\\file.in> C:\\file.out";
proc.StartInfo = new ProcessStartInfo(AppName, args);
proc.Start();
if I paste those arguments into a command window the application runs as expected. proc.Start() does not run as expected.
Any ideas how I can view what Start is actually passing as arguments? My gut feeling is that this is a quotes issue.
The executable launches and hangs, so I'm confident the AppName is getting passed in correctly, it looks like an argument problem.
I tried setting the WorkingDirectory to that of the input and output files as suggested in this question: process.start() arguments but that did not work.
Redirection with the < and > command line operators is a feature that's implemented by the command line processor. Which is cmd.exe. Use its /c argument to execute just a single command:
string args = "/c " + AppName + " < C:\\file.in > C:\\file.out";
proc.StartInfo = new ProcessStartInfo("cmd.exe", args);
proc.Start();
Your args string is exactly what is being passed as arguments to the executable. You can double check it reading your Process ProcessStartInfo.Arguments Property.
Something similar happened to me once, i.e., calling the executable from the command line worked and from code didn't, and it turned out that when called from the command line the executable was running on my PC's [C:] drive, and when called from code it was running on my PC's [E:] drive, which was full!
To check which directory your application is using to run the executable use the Directory.GetCurrentDirectory Method.

Passing and accessing Powershell parameters from C#

I am trying to pass parameters to Powershell script from a C# class. I am running the script using Process.Start.
string powerShellLocation = #"C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe";
ProcessStartInfo psi = new ProcessStartInfo(powerShellLocation);
psi.Arguments = String.Format("{0} {1}", scriptPath, "some_parameter");
The above does not work. Can someone please tell me how to achieve this?
You need to set the parameter name. Something like this should work:
string parameters = string.Format("-FILE {0} -parameter1 \"{1}\"", psFilePath, parameter1Value);
Process powershell = new Process()
{
StartInfo = new ProcessStartInfo("powershell.exe", parameters)
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
}
};
What you have would work. You have not mentioned what you meant by above does not work and what your script is.
I tried the C# code with the Powershell script:
param([string]$a)
write-host "test"
write-host $a
and it gave the output:
test
some_parameter
as expected. There is no need to specify -File and -paramter1 like the other answer mentions, but will depend on what your script does.
Did you set the execution policy to unrestricted or to something that allows you to execute the script. By default Powershell sets scripts to be unrestricted to prevent malicious scripts from running.
Run this command as an administrator when powershell is running:
Get-ExecutionPolicy

Categories

Resources