My powershell script fails to run with the following error:
On this line: -
"Import-AzureRmContext -Path C:\profile.json;"
If I right click the file and "Run with powershell" then the script runs fine.
If I run using PowerShellInstance, get the same error:
Found this code from another StackOverflow Post. Which you can use to execute powershell scripts using command prompt. This worked for me using the below function and call:
ExecuteCommand("powershell -command \" & C:\\PowershellFileName.ps1\"");
public void ExecuteCommand(string Command)
{
ProcessStartInfo ProcessInfo;
Process Process;
ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = true;
Process = Process.Start(ProcessInfo);
}
Related
I am using PsExec to remotely fire a program. I can fire the actual program (not displayed here) or cmd.exe remotely with no problems whatsoever from the command line. When I try to fire it from ASP and C#, it will not trigger the command prompt, even though I am using the same exact string. Here is the string I am using that works every time, and the code that doesn't. Help please!
Working String: C:\psexec \\10.0.0.25 -u Administrator -p password -d -i cmd.exe
Non-working code:
ProcessStartInfo psi = new ProcessStartInfo(#"C:\PsExec.exe")
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
Arguments = #"\\10.0.0.25 -u Administrator -p password -d -i cmd.exe"
};
process.StartInfo = psi;
var success = process.Start();
One option, assuming you have control over the machine, is to setup the psexec command as a Task Scheduler job, then execute the task scheduler job from your ASP app. You can configure the task scheduler to run as an administrator, and when you fire off the job it will run under that credentials. You won't get any output that way though, so if that's an issue there may not be a good choice.
See How to run existing windows 7 task using command prompt for an example of running the task..
It's been a while since I was a system administrator, but if I recall correctly psexec has to be run from an administrative command prompt. Maybe the account your app is running under doesn't have rights to reach across the network and do stuff to a remote machine?
Put this in your Page_Load temporarily:
Response.Write(Environment.UserName);
and run it again, it should show you the name you're looking for at the top of your app.
Well, I am right now doing some automation and have figured out a few things. Please see below code maybe it will help you out
public static void PSExec_Method()
{
try
{
string userName = #"ABC";
string password = "ABC";
string remoteMachine = "ABC";
//How to restart AppPool
//string operation = "stop";
//string apppoolname = "APPPOOL";
//string command = #"%SYSTEMROOT%\System32\inetsrv\appcmd " + operation + " apppool /apppool.name:\"" + apppoolname + "\"";
string command = #"powershell -noninteractive Get-Content C:\tmp\tmp.csv -Head 5";
//string command = #"ipconfig";
string PSPath = #"C:\PSTools\PsExec.exe";
string fullcommand = PSPath + " -u " + userName + " -p " + password + " \\\\" + remoteMachine + " -h cmd.exe /c " + command;
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = fullcommand;
process.Start();
Console.WriteLine(process.StandardOutput.ReadToEnd());
Console.WriteLine(process.StandardError.ReadToEnd());
process.WaitForExit();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
I have a batch file I want to run from a C# windows form. the Batch file is very basic and accepts one parameter
cd C:\Program Files (x86)\Advent\ApxClient
AdvScriptRunner REPRUN -mrgainloss -p%1 -vf -t\\myserver\apx$\pdf\myReport
If i call it in a command prompt, this works fine
C:\Program Files (x86)\Locations\blah>realizedgainloss 123456
that will run just fine, and i get the expected result (it outputs a report run on a third party peice of software). However I cannot for the life of me figure this out with c#. I have the following.
private void button1_Click(object sender, EventArgs e)
{
ExecuteCommand(getCommand());
}
public string getCommand()
{
return "realizedgainloss.bat";
}
static void ExecuteCommand(string command)
{
int exitCode;
ProcessStartInfo processInfo;
Process process;
processInfo = new ProcessStartInfo(command);
//processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
// *** Redirect the output ***
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
processInfo.Arguments = String.Format("{0} {1}", command, "123456");
process = Process.Start(processInfo);
process.WaitForExit();
// *** Read the streams ***
// Warning: This approach can lead to deadlocks, see Edit #2
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
exitCode = process.ExitCode;
Console.WriteLine("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
Console.WriteLine("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
Console.WriteLine("ExitCode: " + exitCode.ToString(), "ExecuteCommand");
process.Close();
}
Its worth noting that if i do not provide a parameter, and change the bat file to be static, with 12345 in place of it's %1, then it runs from C#, so there is something incorrect about how i'm getting the parameters into the bat file...
any thoughts?
You have your batch file name as the command to run and the first parameter of your script. I find it easier and more reliable to use cmd.exe as the command to run and invoke it with the /C argument. Doing it this way you should make sure your working directory is set correctly as well.
processInfo = new ProcessStartInfo("cmd.exe");
processInfo.Arguments = String.Format("/C {0} {1}", command, "123456");
processInfo.WorkingDirectory = yourWorkingDirectory;
Trying to call a perl script from my c# app. The perl script has a prompt that requires the user to enter something into it. I can't seem to get it to display. This is the function i use to call it. I have another function that sets the System.Enviroment.SetEnvironmtVariable to have the path of "C:\Perl\bin\;" along with other ones needed for other process'
private void getRevisionAndUpdate()
{
Process myProcess = new Process();
myProcess.StartInfo.FileName = "cmd.exe";
myProcess.StartInfo.WorkingDirectory = #"the directory that has the perl script";
myProcess.StartInfo.Arguments = #"/c SaidPerlScript.pl";
myProcess.StartInfo.UseShellExecute = false;
myProcess.Start();
myProcess.WaitForExit();
}
as i said before it seems to run, but it will either just open the script in a notepad or do nothing at all. Also should note i've tried running cmd.exe and perl.exe. cmd seems to open it in notepad and perl doesn't display the prompt it should.
Not quite sure why you're trying to run cmd.exe, but it works if you run it via perl.exe (my script is called a.pl and prints hello):
static void Main(string[] args)
{
Process myProcess = new Process();
myProcess.StartInfo.FileName = "perl.exe";
myProcess.StartInfo.WorkingDirectory = #".\";
myProcess.StartInfo.Arguments = #"a.pl";
myProcess.StartInfo.UseShellExecute = false;
myProcess.Start();
myProcess.WaitForExit();
}
and it also correctly reads STDIN. For reference this is a.pl:
print("Hello\n");
my $a = <STDIN>;
print "You entered " . $a . "\n";
Similar question was asked at least a dozen times on SO and it looks that now I have exhausted most of the proposed solutions but still unable to complete the task successfully.
So what I have is the following command that I want to run in cmd:
xcopy /q C:\fileName.txt \\VMNAME\C$\destFolder /Y /E
But I need it to be executed with certain credentials. So what I was doing manually is entering the below command first:
runas /user:<domainName>\<userName> cmd
That was opening a separate cmd window and I was running the first (xcopy) command in that window.
What I have at the moment:
string strCmdText = string.Format(#"xcopy /q {0} {1} /Y /E", source, destination);
ProcessStartInfo procStartInfo = new ProcessStartInfo();
procStartInfo.RedirectStandardError = true;
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.FileName = "runas";
procStartInfo.Arguments = String.Format(#"/user:<domainName>\<userName> cmd " + strCmdText);
Process.Start(procStartInfo);
Where the source and destination are of the below structure:
source = "C:\\somePath\\fileName.txt"
destination = "\\\\<VMName>\\C$\\somePath\\"
I have also tried defining procStartInfo with:
procStartInfo.Verb = "runas";
Instead of:
procStartInfo.FileName = "runas";
With similar results.
At the moment, when I run the above code, it does not return any error but doesn't do what's expected either. Am I missing something or this approach is wrong?
I want to execute a batch command and save the output in a string, but I can only execute the file and am not able to save the content in a string.
Batch file:
#echo off
"C:\lmxendutil.exe" -licstatxml -host serv005 -port
6200>C:\Temp\HW_Lic_XML.xml notepad C:\Temp\HW_Lic_XML.xml
C# code:
private void btnShowLicstate_Click(object sender, EventArgs e)
{
string command = "'C:\\lmxendutil.exe' -licstatxml -host lwserv005 -port 6200";
txtOutput.Text = ExecuteCommand(command);
}
static string ExecuteCommand(string command)
{
int exitCode;
ProcessStartInfo processInfo;
Process process;
processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
// *** Redirect the output ***
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
process = Process.Start(processInfo);
process.WaitForExit();
// *** Read the streams ***
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
exitCode = process.ExitCode;
process.Close();
return output;
}
I want the output in a string and do this directly in C# without a batch file, is this possible?
Don't need to use "CMD.exe" for execute a commandline application or retreive the output, you can use "lmxendutil.exe" directly.
Try this:
processInfo = new ProcessStartInfo();
processInfo.FileName = "C:\\lmxendutil.exe";
processInfo.Arguments = "-licstatxml -host serv005 -port 6200";
//etc...
Do your modifications to use "command" there.
I hope this helps.
It doesn't look to me like your batch file will produce any output. If you run it in the command line, do you see an output? You have the redirection > operator in your bat file line, so it seems like you're sending output to the xml file.
If you have saved the output to an xml file, maybe you should just load that using C# once your process exits.