Passing variables from C # to Powershell

I am working on a C # project which is to capture a string variable (path to a file) and pass it to a PowerShell script to execute further commands with it. I look online and through Stack and could not find something that works for me ...

Here is my C # code that is standing right now:

string script = System.IO.File.ReadAllText(@"C:\my\script\path\script.ps1"); using (Runspace runspace = RunspaceFactory.CreateRunspace()) { runspace.Open(); PowerShell ps = PowerShell.Create(); ps.Runspace = runspace; ps.AddScript(script); ps.Invoke(); ps.AddCommand("LocalCopy"); foreach (PSObject result in ps.Invoke()) { Console.WriteLine(result); } } 

Here is my PowerShell script:

 Function LocalCopy { Get-ChildItem -path "C:\Users\file1\file2\file3\" -Filter *.tib -Recurse | Copy-Item -Destination "C:\Users\file1\file2\local\" } 

What I want to do is replace the first part of the script: "C:\Users\file1\file2\file3\" with a replacement (what I am assuming) is a variable that I could pass from C # code to a PowerShell script. I am very new to working with PowerShell and am not quite sure how I will do something similar.

--- --- EDIT

I'm still having problems with my code, but I am not getting any errors. I believe this is because the variable still does not go through ...

C # code:

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

 using (Runspace runspace = RunspaceFactory.CreateRunspace()) { runspace.Open(); PowerShell ps = PowerShell.Create(); ps.Runspace = runspace; ps.AddScript(script); ps.Invoke(); ps.AddArgument(FilePathVariable); ps.AddCommand("LocalCopy"); foreach (PSObject result in ps.Invoke()) { Console.WriteLine(result); } } 

PowerShell Code:

 Function LocalCopy { $path = $args[0] Get-ChildItem -path $path -Filter *.tib -Recurse | Copy-Item -Destination "C:\Users\file1\file2\local\" } 

Any help would be greatly appreciated. Thanks!

+4
source share
2 answers

I would go along the route that Anand showed to go through your script. But to answer the question asked by your name, here is how you pass a variable from C #. Well, this is really how you set the variable in the PowerShell engine.

 ps.Runspace.SessionStateProxy.SetVariable("Path", @"C:\Users\file1\file2\file3\"); 

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

Update: based on your comments, try the following:

 runspace.Open(); PowerShell ps = PowerShell.Create(); ps.Runspace = runspace; ps.AddScript(script, false); // Use false to tell PowerShell to run script in current // scope otherwise LocalCopy function won't be available // later when we try to invoke it. ps.Invoke(); ps.Commands.Clear(); ps.AddCommand("LocalCopy").AddArgument(FilePathVariable); ps.Invoke(); 
+6
source
 ps.AddArgument("C:\Users\file1\file2\file3\"); 

you can use args to extract an argument in powershell.

 $path = $args[0] 

MSDN

+5
source

Source: https://habr.com/ru/post/1496804/


All Articles