2

I want to call PowerShell script from my C# project but it wont work.

When I run the code I don't get any errors(or I don't know where to find them). I also tried to run script from cmd and script works fine.

My execution policy is set to unrestricted so that is not a problem.

I double checked paths, so these are not problem either.

C# code:

string scriptPath = @"C:\Users\jmiha\Desktop\test.ps1";
var parameters = new List<String>();
parameters.Add("test");
PowerShell ps = PowerShell.Create();
ps.AddScript(scriptPath);
ps.AddParameters(parameters);
ps.Invoke();

PowerShell script:

param(
    [Parameter(Mandatory = $true)]
    [String]$param
)
Add-Content 'c:\users\jmiha\desktop\test.txt' $param

When I open the test.txt it is empty.

3
  • 3
    ps.AddScript(scriptPath); --> ps.AddCommand(scriptPath); Commented Apr 23, 2019 at 15:57
  • @MathiasR.Jessen, Then what is the diff between them ? Commented Apr 23, 2019 at 17:03
  • 3
    @PrasoonKarunanV: .AddScript() is poorly named; .AddScriptBlock() would have made more sense: you pass it a self-contained snippet of PowerShell code - entire commands including their arguments; .AddCommand() adds a single command name or path (including, if applicable, a script file), whose arguments must be added separately. Commented Apr 23, 2019 at 20:30

1 Answer 1

2

AddScript is meant for arbitrary code, not a command/parameter syntax. You could use something like

ps.AddScript("Test-Path C:\temp").Invoke()

and it works.

If you want to bind parameters and the like, you need to use AddCommand which lets you interact with the commands like they objects they are and will bind your parameter:

using (PowerShell powershell = PowerShell.Create())
    powershell
        .AddCommand(@"C:\Temp\test.ps1")
        .AddParameter("param", "TEST")
        .Invoke()

p.s. the documentation of System.Management.Automation.dll is terrible.

Sign up to request clarification or add additional context in comments.

1 Comment

It solved the problem, thank you!!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.