Passing Variables from C# to Powershell
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:
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 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.
Any help would be much appreciated. Thanks!
No comments:
Post a Comment