Search code examples
c#powershellpowershell-sdk

C# won't run PowerShell script


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.


Solution

  • 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.