question

SivaMani-0897 avatar image
0 Votes"
SivaMani-0897 asked karenpayneoregon answered

Run PowerShell Script C#

I have the below code,

var process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.StartInfo.FileName = "powershell.exe";
process.StartInfo.Arguments = psfile;
process.Start();
process.WaitForExit();

psfile is the path of PowerShell script file.

Nothing happened when I run this code. Anything wrong here?





dotnet-csharpwindows-server-powershell
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Castorix31 avatar image
0 Votes"
Castorix31 answered SivaMani-0897 commented

It is often the Wow redirection.
Try to add before :

             bool bWow64 = false;
             IsWow64Process(Process.GetCurrentProcess().Handle, out bWow64);
             if (bWow64)
             {
                 IntPtr OldValue = IntPtr.Zero;
                 bool bRet = Wow64DisableWow64FsRedirection(out OldValue);
             }

With declarations :

     [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
     private static extern bool IsWow64Process(IntPtr hProcess, out bool Wow64Process);

     [DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
     private static extern bool Wow64DisableWow64FsRedirection(out IntPtr OldValue);
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@Castorix31 Thanks for the response. I added Execution Policy and it worked. Now I have another problem. That PS script has multiple parameters. I wanted pass values from c# code. It is not working for me. Please suggest me.

process.StartInfo.Arguments = psfile+" -site "+site+" -file "+file+" -folder "+folder;

0 Votes 0 ·
karenpayneoregon avatar image
1 Vote"
karenpayneoregon answered

It's possible that a policy disallows a PowerShell script to run from .NET while the policy does or does not affect running a script from a ps1 file. To test this out try running with a visible window. I see nothing wrong with the code as it's pretty much what I've done as seen here.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.