![](/img/trans.png)
[英]Passing variables to powershell from C# : Output file location variables
[英]Passing Variables from C# to Powershell
我正在研究一个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);
}
}
这是我的PowerShell脚本:
Function LocalCopy
{
Get-ChildItem -path "C:\Users\file1\file2\file3\" -Filter *.tib -Recurse |
Copy-Item -Destination "C:\Users\file1\file2\local\"
}
我想做的是将脚本的第一部分: "C:\\Users\\file1\\file2\\file3\\"
替换为(我假设是)可以从C#代码传递给PowerShell脚本。 我对使用PowerShell非常陌生,并且不确定如何做这样的事情。
- -编辑 - -
我的代码仍然有问题,但没有收到任何错误。 我相信这是因为变量仍然没有通过...
C#代码:
字符串脚本= 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代码:
Function LocalCopy
{
$path = $args[0]
Get-ChildItem -path $path -Filter *.tib -Recurse |
Copy-Item -Destination "C:\Users\file1\file2\local\"
}
任何帮助将非常感激。 谢谢!
我会选择Anand所示的路线,将路径传递到您的脚本中。 但是要回答标题所提出的问题,这是如何从C#传递变量。 好的,这就是您在PowerShell引擎中设置变量的方式。
ps.Runspace.SessionStateProxy.SetVariable("Path", @"C:\Users\file1\file2\file3\");
注意:在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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.