Passing Variables from C# to Powershell

Question:

I am working on a C# project that that is supposed to grab a string variable (file path) and pass it to PowerShell script to have further commands done with it. I have been looking around online and through Stack and have not been able to find something that works for me…

Here is my C# code as it stands right now:

Here is my PowerShell script:

What I want to do is have the first part of the the script: "C:\Users\file1\file2\file3\" replaced with (what i am assuming would be) a variable that I could pass from the C# code to the PowerShell script. I am very new to working with PowerShell and am not quite sure how I would go about doing something like this.

—EDIT—

I am still having issues with my code, but i am not getting any errors. I believe that it is because the variable is still not being passed through…

C# code:

string script = System.IO.File.ReadAllText(@”C:\my\script\path\script.ps1″);

PowerShell code:

Any help would be much appreciated. Thanks!

Answer:

I would go the route Anand has shown to pass a path into your script. But to answer the question posed by your title, here’s how you pass variable from C#. Well this is really how you set the variable in the PowerShell engine.

Note: in C# for file paths you really want to use verbatim @ strings.

Update: based on your comments, try this:

Source:

Passing Variables from C# to Powershell by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply