Home > Mobile >  How to debug "invoking" Powershell (ps1) from C# file
How to debug "invoking" Powershell (ps1) from C# file

Time:11-25

I am trying to invoke Powershell file from C# Visual Studio solution.

Apparently, while debugging, it appears that it does not do anything when it hits the line where it invoke PS1 file.

I am getting this message:

enter image description here

I have these lines inside C#:

using System.Management.Automation;

PowerShell ps = PowerShell.Create();
ps.AddScript(File.ReadAllText(@"C:\Users\Justin\source\repos\HttpTrigger_1119\HttpTrigger_1119\list.ps1")).Invoke();

However, when the break point hits the next line, it did not show errors: enter image description here

My next attempt was putting breakpoint inside ps1 file itself.

But, it appears that it did not even stop at the breakpoint of ps1 file.

Since, it did not hit the breakpoint inside ps1 file, there might be something missing invoking PS1 file, no?

Anything to add from existing two lines?

PowerShell ps = PowerShell.Create();
ps.AddScript(File.ReadAllText(@"C:\Users\Justin\source\repos\HttpTrigger_1119\HttpTrigger_1119\list.ps1")).Invoke();

CodePudding user response:

Regarding the question "How to debug..."

Refactor your code:

PowerShell ps = PowerShell.Create();
ps.AddScript(File.ReadAllText(@"C:\Users\Justin\source\repos\HttpTrigger_1119\HttpTrigger_1119\list.ps1")).Invoke();

To something you can observe in the debugger:

var ps1Script = File.ReadAllText(...); 
var newPs = ps.AddScript(ps1Script); 
var psResult = newPs.Invoke();

And step through your code to ensure it's doing what you expect it to.

  • Related