将变量从C#传递给PowerShell:输出文件位置变量

时间:2012-06-12 14:48:47

标签: c# powershell

我最近开始使用C#来调用powershell脚本,并取得了一些成功:)

$spWeb = Get-SPWeb -Identity http://127.0.0.1 
$listTemplate = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary 
$spWeb.Lists.Add($args, "", $listTemplate) > $myDirectory

$spWeb.Lists.Add返回SharePoint GUID。

问题:

  

我只想传入GUID所在的目录/文件名   写的。怎么可能这样做?

我已经在MSDN论坛上发布了这个帖子:http://goo.gl/5p0oz但由于看似死路一条线程,我继续搜索stackoverflow。这篇文章是通过MSDN响应找到的信息的累积收集。

1 个答案:

答案 0 :(得分:1)

您可以尝试使用Set-Content cmdlet,就像这样。您需要将$ myFile作为字符串传递,Set-Content将为您完成剩下的工作 -

在你的脚本中,MyScript.ps1在这里,你将拥有这段代码 -

param([string]$parameter, [string]$myFile)
try
{
    $spWeb = Get-SPWeb -Identity http://127.0.0.1 
    $listTemplate = [Microsoft.SharePoint.SPListTemplateType]::DocumentLibrary 
    $guid = $spWeb.Lists.Add($parameter, "", $listTemplate)
    $guid | Set-Content $myFile
}
catch
{
    throw ("Failed. The error was: '{0}'." -f $_ )
}

如何运行: 打开Powershell提示符并输入此

.\MyScript.ps1 "someparam1" "D:\Output.txt"

C#位 -

private PowerShell _ps;
_ps = PowerShell.Create();

var parameter = new List<string>
                                {
                                    parameter,
                                    myFile
                                };

var sr = new StreamReader(@"C:\MyScript.ps1");
_ps.AddScript(sr.ReadToEnd()).AddParameters(parameter);
_ps.Invoke();
相关问题