我正在Powershell中编写一个脚本,该脚本中我想从C#代码中设置一个变量。
我在Install.PS1
文件中有Powershell脚本。
这段代码在Install.PS1
文件中
$guid = (Get-ChildItem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall).Name |
% { $path = "Registry::$_"; Get-ItemProperty $path } |
Where-Object { $_.DisplayName -like $filter } |
Select-Object -Property PsChildName
我想通过C#代码设置$filter
的值。
答案 0 :(得分:0)
这根本行不通。
与此Cmdlet一起使用的第一个无名参数是参数“ FilterScript”。此参数需要一个Scriptblock
作为参数值。这个地方不允许使用C#代码。
您可以在此处找到有关Where-Object
的更多信息:https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/where-object?view=powershell-6
答案 1 :(得分:0)
您可以使用InitialSessionState
object以编程方式预先准备变量:
using System.Management.Automation;
using System.Management.Automation.Runspaces;
// prepare the variables needed
InitialSessionState iss = InitialSessionState.CreateDefault2();
iss.Variables.Add(new SessionStateVariableEntry("filter", "*wildcardfi?ter*", "Product name filter value"));
// execute the script
using (var ps = PowerShell.Create(iss))
{
ps.AddScript("your script goes here");
foreach (var result in ps.Invoke())
{
var childname = result.Properties["PsChildName"].Value;
// do what you please with childname in here
}
}