将变量从C#传递给Powershell

sca*_*t17 4 c# powershell visual-studio-2010

我正在开发一个C#项目,它应该获取一个字符串变量(文件路径)并将其传递给PowerShell脚本以完成其他命令.我一直在网上和通过Stack环顾四周,但却找不到适合我的东西......

这是我现在的C#代码:

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);
    }
}                   
Run Code Online (Sandbox Code Playgroud)

这是我的PowerShell脚本:

Function LocalCopy
{
    Get-ChildItem -path "C:\Users\file1\file2\file3\" -Filter *.tib -Recurse | 
    Copy-Item -Destination "C:\Users\file1\file2\local\"
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是拥有脚本的第一部分:"C:\Users\file1\file2\file3\"替换为(我假设将是)我可以从C#代码传递给PowerShell脚本的变量.我对使用PowerShell非常陌生,我不太确定如何做这样的事情.

- -编辑 - -

我的代码仍有问题,但我没有收到任何错误.我相信这是因为变量仍未通过......

C#代码:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

PowerShell代码:

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

任何帮助将非常感激.谢谢!

Kei*_*ill 6

我会走的路线Anand已经证明可以通过一条路径进入你的脚本.但是要回答你的标题提出的问题,这里是你如何从C#传递变量.那么这就是你在PowerShell引擎中设置变量的方法.

ps.Runspace.SessionStateProxy.SetVariable("Path", @"C:\Users\file1\file2\file3\");
Run Code Online (Sandbox Code Playgroud)

注意:在文件路径的C#中,您确实想要使用逐字@字符串.

更新:根据您的评论,试试这个:

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();
Run Code Online (Sandbox Code Playgroud)


Ana*_*and 5

ps.AddArgument("C:\Users\file1\file2\file3\");
Run Code Online (Sandbox Code Playgroud)

你可以使用args来获取powershell中的参数.

$path = $args[0]
Run Code Online (Sandbox Code Playgroud)

MSDN