Passing and accessing Powershell parameters from C# - 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

Related

How to pass arguments to command line utility using c#?

I'm writing an application, and at one point it launches win-acme and needs to pass some parametres to it. I'm successfully opening powershell and launching win-acme, but it doesn't pass arguments to it. So, I have this code:
Process wacsProcess = Process.Start(new ProcessStartInfo
{
FileName = #"C:\Windows\System32\WindowsPowershell\v1.0\powershell.exe",
Arguments = (#"cd C:\inetpub\letsencrypt ; .\wacs.exe ; N"),
RedirectStandardOutput = true,
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden
});
File.WriteAllText(".\\OutPutAfterFirstLaunch.txt",
wacsProcess.StandardOutput.ReadToEnd());
It opens command-line utility, but doesn't give it the last parametr "N". I guess that is because I'm passing this parametr to the powershell, but it's still working with win-acme.
It looks like this:
Is there a way to pass an argument to the command line utility using C#?
This is how this application is designed. It is meant to be interactive for new certificates. Please see the documentation with all of the allowed command-line arguments: https://www.win-acme.com/reference/cli
Is there a particular reason that you must launch the process from powershell?
You should be able to read the stdout of the process if you launch it directly the same way as if you were reading the output from your powershell window (the output powershell displays is just the stdout of the process anyways.)
You can also try passing the N parameter with the executable,
Arguments = (#"cd C:\inetpub\letsencrypt ; .\wacs.exe N;"),

Is there a way to run a .NET Core Service that uses OS authentication to run RMAN backups as systemd?

I have a service set up in C#/.NET Core and part of its functionality is to launch RMAN for Oracle at a specified time each day. These functionalities all work perfectly running as the Oracle user but not as root or running as systemd(even if I include the parameter to run as oracle in the init file).
Error when trying to run RMAN as root:
Error as Root
ORA-12162: TNS:net service name is incorrectly specified
The code in C#:
string oraHome = Environment.GetEnvironmentVariable("ORACLE_HOME");
//execute powershell cmdlets or scripts using command arguments as process
ProcessStartInfo processInfo = new ProcessStartInfo
{
FileName = $"{oraHome}/bin/rman",
Arguments = $"NOCATALOG TARGET / CMDFILE {RMANObjects.Backup}RMAN_{RMANObjects.sn}.rcv LOG {RMANObjects.Backup}backup_log_{RMANObjects.sn}.txt",
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
//start powershell process using process start info
Process process = new Process();
process.StartInfo = processInfo;
process.Start();
RMANandLogMover init/service file
[Unit]
Description=RMANandLogMover
DefaultDependencies=no
[Service]
Type=notify
WorkingDirectory=/home/oracle/app/RMANandLogMover/8.25Logmover
ExecStart=/home/oracle/app/RMANandLogMover/8.25Logmover/RMANandLogMover
Environment=ORACLE_HOME=/home/oracle/app/product/19.0.0/dbhome_1
User=oracle
Group=backupdba
RemainAfterExit=yes
[Install]
WantedBy=default.target
the problem here is not all environment variables are set. I suggest you to invoke oraenv first and make sure that you are using oracle's os user, not any other
export ORACLE_HOME=<path>
export ORACLE_SID=orcl
export ORAENV_ASK=NO
. oraenv
first code this, then run RMAN :)

Calling Pyenv Python From C#

I'm trying to run Python from C# via a command line process.
System.Diagnostics.Process proc = new System.Diagnostics.Process {
StartInfo = new System.Diagnostics.ProcessStartInfo {
FileName = "/Users/username/.pyenv/shims/python",
Arguments = cmd+" "+args,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
}
};
I derived the FileName from using which:
username$ which python
/Users/username/.pyenv/shims/python
However, running python --version from the terminal, and then again through the C# process, yield different results:
username$ python -V
Python 2.7.11
And C#:
Python 2.7.10
I understand the base problem - that it's calling another version of Python, probably the base one that came from Apple. But what I don't understand is why, because as I understand it I'm telling it to call python from pyenv directly. Is there a way to get C# to use the same python executable I'm using from the terminal?
My bet is that the python shim depends on something else in your environment, and you should probably figure out what it’s eventually running, then call that directly.
According to the pyenv documentation, it's probably at:
$(pyenv root)/versions/2.7.11/bin/python
You might also be able to find out by running the shim with set -x, and looking at the command trace:
(set -x; python --version)

Process.Start cmd results in "is not recognized"

When launching an application directly, the application is launched, but when launched through cmd - it's not.
For example:
Works:
Process.Start("firefox");
Doesn't work:
Process.Start(
new ProcessStartInfo
{
FileName = "cmd",
Arguments = "/k firefox"
});
I've tried setting UseShellExecute to true, but to no avail. I still get:
'firefox' is not recognized as an internal or external command,
operable program or batch file.
So, yes, I can specify the complete path. But is there a way to avoid that? Or in other words - what's the difference between the two that makes the second fail?
Haven't tested it but I guess you are probably looking for the start command:
Process.Start(
new ProcessStartInfo
{
FileName = "cmd",
Arguments = "/k start firefox"
});
As a tip, simply run "firefox" in a command prompt -> you'd get the same error message.

Mono Start Process mdtool Close the Caller

In a console app on Mono/OSX I want to call the mdtool to build an iOS project. I succeed to have the right command line arguments and it runs correctly in bash shell script.
Now If I call it with the Process/ProcessStartInfo classes in my console app, after the build I got this and my programm exits.
Press any key to continue... logout
[Process completed]
Here's the code to call mdtool:
var buildArgs = string.Format("...");
var buildiOSproject = new ProcessStartInfo
{
FileName = "/Applications/MonoDevelop.app/Contents/MacOS/mdtool",
UseShellExecute = false,
Arguments = buildArgs
};
var exeProcess = Process.Start(buildiOSproject);
exeProcess.WaitForExit();
//code here never called
I got my answer on the Xamarin forums (http://forums.xamarin.com/discussion/267/calling-mdtool-trough-processstartinfo#latest) but it seems a problem with the debugger so I switch off the "Run on external console" property in the options of my project and it's working now.
Try adding the following to your StartInfo initializer. I faced the same problem with another tool when it exited. Although I had already used RedirectStandardOutput and RedirectStandardError, I got it fixed only after adding RedirectStandardInput also.
buildiOSproject.StartInfo = new ProcessStartInfo
{
...
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
...
}

Categories

Resources