簡體   English   中英

將變量從C#傳遞到Powershell

[英]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();
ps.AddArgument("C:\Users\file1\file2\file3\");

您可以使用args在powershell中獲取參數。

$path = $args[0]

MSDN

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM