WPF& PowerShell - 将变量从PS传递到C#或修改值

时间:2016-02-29 17:51:25

标签: c# wpf powershell

我需要使用PowerShell执行验证,并根据结果在WPF应用程序中执行操作。我知道我可以从PowerShell修改TextBlocks但是当我尝试从PowerShell中修改WPF变量的值时没有任何反应。

这是一个例子。

MainWindow.xaml:

    <Window x:Class="Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Test"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Margin="74,76,0,0" TextWrapping="Wrap" Text="false" VerticalAlignment="Top" Height="177" Width="371"/>
    </Grid>
</Window>

MainWindow.xaml.cs:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Text.RegularExpressions;
using System.IO;

namespace Test
{
    public partial class MainWindow : Window
    {
        private bool exists = false;

        public MainWindow()
        {
            InitializeComponent();

            // Setup PowerShell Environment
            Runspace runSpace = RunspaceFactory.CreateRunspace();
            runSpace.ThreadOptions = PSThreadOptions.UseCurrentThread;
            runSpace.Open();
            runSpace.SessionStateProxy.SetVariable("exists", exists);
            PowerShell ps = PowerShell.Create();
            ps.Runspace = runSpace;
            string check = "$exists = true";
            ps.AddScript(check);
            // Execute
            ps.Invoke();
            runSpace.Close();

            if (exists == true)
            {
                textBlock.Text = "It is true!";
            }
        }
    }
}

如何在进行一些验证后从PowerShell中修改C#/ WPF变量?这甚至可能吗?

我不想为临时变量创建随机文本块/标签/文本框。

2 个答案:

答案 0 :(得分:0)

首先,exists是值类型。要从PowerShell更新exists,您必须通过引用PowerShell脚本来传递它。我可能错了,但似乎不太可能。即使有可能,我仍然不会推荐它。操纵这样的状态似乎很严重。我认为更好的方法是将要验证的数据传递给PowerShell脚本,并将验证结果返回给C#。您可以根据该结果在C#中修改变量状态。

以下是我在LinqPad中使用输出运行的代码的略微修改版本:

var exists = true;
Runspace runSpace = RunspaceFactory.CreateRunspace();
runSpace.ThreadOptions = PSThreadOptions.UseCurrentThread;
runSpace.Open();

PowerShell ps = PowerShell.Create();
ps.Runspace = runSpace;
string validation = @"
    # Perform some validation.

    # For the purposes of this demonstration I am going to pretend
    # that validation failed and set 'result' to false.
    $result = $false

    # Return 'result'
    $result
";
ps.AddScript(validation);

// Write the state of `exists` to the console before invoking PowerShell.
Console.WriteLine("exists: " + exists.ToString());

// Execute
var result = ps.Invoke();

// Update exists based on the result of the validation.
exists = bool.Parse(result[0].ToString());

// Or you can use 'GetVariable' to get the result back from PowerShell:
// exists = bool.Parse(runSpace.SessionStateProxy.GetVariable("result").ToString());

// Write the state to the console after invoking PowerShell.
Console.WriteLine("exists: " + exists.ToString());

以下是写入控制台的结果:

  

存在:真实   存在:错误

答案 1 :(得分:0)

使用Mike的建议我设法从PS获取变量,甚至不必映射它。像这样:

using System;
using System.Windows;
using System.Windows.Controls;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Text.RegularExpressions;
using System.IO;

namespace Test
{
    public partial class MainWindow : Window
    {
        public bool itExists = false;

        public MainWindow()
        {
            InitializeComponent();

            // Setup PowerShell Environment
            Runspace runSpace = RunspaceFactory.CreateRunspace();
            runSpace.ThreadOptions = PSThreadOptions.UseCurrentThread;
            runSpace.Open();
            PowerShell ps = PowerShell.Create();
            ps.Runspace = runSpace;
            string check = "$itExists = $TRUE";
            ps.AddScript(check);
            // Execute
            ps.Invoke();

            var result = runSpace.SessionStateProxy.PSVariable.GetValue("itExists").ToString();

            runSpace.Close();

            itExists = result.Equals("True");

            if (itExists)
            {
                textBlock.Text = "It is true!";
            }
        }
    }
}