gpt4 book ai didi

c# - Powershell 和 C# : add a parameter script in a pipeline

转载 作者:行者123 更新时间:2023-11-30 23:04:56 25 4
gpt4 key购买 nike

我最近开始学习 PowerShell 和 C#。我想在带有 visual studio 的网络应用程序中使用它。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;


namespace Extraction_test.Controllers
{
public class HomeController : Controller
{
public string Index() //PowershellExtract()
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(@"$filepath=""C:\Users\myusernamefolder\Downloads\ReadExcel\Test.xlsx"";");
pipeline.Commands.Add("Param([string]$filepath;)");
string scriptpath = "[System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo] \"en-US\";" +
"$Excel = New-Object -ComObject Excel.application;" +
"$Excel.visible=$True;" +
"$Workbook=$Excel.Workbooks.open($filepath);" +
"$Worksheet=$WorkbookSheets.item(\"Feuil1\");" +
"$Worksheet.activate();" +
"$col = 4;" +
"$lines = @(5,6,7,9);" +
"foreach ($line in $lines) { $global:output = $Worksheet.Cells.Item($line,$col).Value(); }" +
"$global:test='test string value'; " +
"$workbook.Close();" +
"$Excel.Quit();";
pipeline.Commands.AddScript(scriptpath);
Collection<PSObject> results = pipeline.Invoke();
var result = runspace.SessionStateProxy.PSVariable.GetValue("test");
//var result = runspace.SessionStateProxy.PSVariable.GetValue("test");
return result.ToString();

}
}
}

但是,我无法在任何地方找到在管道中添加参数脚本的方法

pipeline.Commands.Add("Param([string]$filepath;)");

提前致谢!

最佳答案

如果单独创建Command对象,可以给它添加一个CommandParameter:

Pipeline pipeline = runspace.CreatePipeline();    
string scriptFile = Path.Combine(ScriptDir, scriptpath);
Command scriptCommand = new Command(scriptFile);

CommandParameter commandParm = new CommandParameter("name", "value");
scriptCommand.Parameters.Add(commandParm);
pipeline.Commands.Add(scriptCommand);
pipeline.Invoke()

关于c# - Powershell 和 C# : add a parameter script in a pipeline,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49064581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com