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.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • 3
    `ps.AddScript(scriptPath);` --> `ps.AddCommand(scriptPath);` – Mathias R. Jessen Apr 23 '19 at 15:57
  • @MathiasR.Jessen, Then what is the diff between them ? – Prasoon Karunan V Apr 23 '19 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. – mklement0 Apr 23 '19 at 20:30

1 Answers1

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.

Maximilian Burszley
  • 18,243
  • 4
  • 34
  • 63