简体   繁体   中英

How to Set variable in powershell script from c#

I'm writing a script in Powershell in which I want to set a variable from C# code.

I have the Powershell script in Install.PS1 file. This code is in the Install.PS1 file

$guid = (Get-ChildItem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall).Name | 
    % { $path = "Registry::$_"; Get-ItemProperty $path } | 
        Where-Object { $_.DisplayName -like $filter } | 
            Select-Object -Property PsChildName

I want to set the value for $filter from C# code.

This simply does not work.

The nameless first parameter you use with this Cmdlet is the parameter "FilterScript". This Parameter needs a Scriptblock as parameter value. There is no C#-Code allowed at this place.

You can find more information about Where-Object here: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/where-object?view=powershell-6

You can pre-stage variables programmatically with an 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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM