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!
source share