![](/img/trans.png)
[英]Using to get PS script name from a C# DLL? Getting "Object reference not set to an instance of an object."
[英]Calling ps script file in c# using automation dll
我正在嘗試使用System.Management.Automation
在C#中使用參數調用Powershell腳本文件,如下所示:
using (var ps = PowerShell.Create())
{
try
{
var script = System.IO.File.ReadAllText("MyPsFile.ps1");
ps.Commands.AddScript(script);
ps.AddScript(script);
ps.AddParameter("MyKey1", value1);
ps.AddParameter("MyKey2", value2);
var results = ps.Invoke();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
Powershell文件如下所示:
function MyFunction {
Param (
[Parameter(Mandatory=$true)][string] $MyKey1,
[Parameter(Mandatory=$true)][string] $MyKey1,
)
Process {
..do some stuff
}
}
MyFunction $args[0] $args[1]
如果我像這樣在Powershell中運行腳本文件:
powershell -file MyPsFile.ps1 "Value1" "Value2"
工作正常。 但是從C#中調用文件不起作用。 知道為什么嗎?
所以我更新了這樣的代碼
var runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
var runSpaceInvoker = new RunspaceInvoke(runspace);
runSpaceInvoker.Invoke("Set-ExecutionPolicy Unrestricted");
// create a pipeline and feed it the script text
var pipeline = runspace.CreatePipeline();
var command = new Command(@". .\MyScript.ps1");
command.Parameters.Add("MyParam1", value1);
command.Parameters.Add("MyParam2", value2);
pipeline.Commands.Add(command);
pipeline.Invoke();
runspace.Close();
但是我得到了錯誤的Powershell ps1文件“未被識別為cmdlet,函數,可操作程序或腳本文件。”
我發現此Powershell ps1文件“未被識別為cmdlet,函數,可操作程序或腳本文件。”
但這並沒有解決問題。 知道還有什么可能導致此錯誤嗎?
終於我找到了解決方案。 兩件事:這段代碼解決了“未被識別為cmdlet,函數,可操作程序或腳本文件的錯誤。這要歸功於從c#調用powershell函數的問題
using (var runspace = RunspaceFactory.CreateRunspace())
{
try
{
var script = File.ReadAllText("MyScript.ps1");
runspace.Open();
var ps = PowerShell.Create();
ps.Runspace = runspace;
ps.AddScript(script);
ps.Invoke();
ps.AddCommand("MyFunction").AddParameters(new Dictionary<string, string>
{
{ "Param1" , value1},
{ "Param2", value2},
{ "Param3", value3},
});
foreach (var result in ps.Invoke())
{
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
重要的是,我還必須從腳本文件中刪除進程包裝器屬性。
****MyScripts.ps1
function MyFunction
{
Param (
[Parameter(Mandatory=$true)][string] myParam1,
[Parameter(Mandatory=$true)][string] myParam2,
[Parameter(Mandatory=$true)][string] myParam3,
)
// Removing the Process wrapper solved the problem, the code didn't run with it
Process {
//DOSTUFF
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.