XAML GUI 到带有变量的 Powershell [英] XAML GUI to Powershell with variables

查看:27
本文介绍了XAML GUI 到带有变量的 Powershell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

超级用户的一位同事让我进入了本指南 关于为 powershell 脚本创建 GUI 但是我是这个领域的新手,所以我需要一些关于编码的指导.

A fellow member on Superuser got me onto this guide on creating a GUI to a powershell script however I am new to this area so I need a little guidance on the coding.

这是Visual Studio 2015生成的XAML代码;

This is the XAML code generated by Visual Studio 2015;

<Window x:Name="Title" x:Class="WpfApplication1.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:WpfApplication1"
    mc:Ignorable="d"
    Title="New Mailbox" Height="400" Width="420">
<Grid>
    <Image x:Name="image" HorizontalAlignment="Left" Height="100" Margin="14,10,0,0" VerticalAlignment="Top" Width="386" Source="C:\Users\Daniel Neocleous\Documents\Visual Studio 2015\Projects\WpfApplication1\WpfApplication1\Images\SibelcoLogo.png"/>
    <RadioButton x:Name="radioButton" Content="Step 1" HorizontalAlignment="Left" Margin="150,125,0,0" VerticalAlignment="Top"/>
    <RadioButton x:Name="radioButton_Copy" Content="Step 2" HorizontalAlignment="Left" Margin="217,125,0,0" VerticalAlignment="Top"/>
    <Button x:Name="button" Content="Create Mailbox" HorizontalAlignment="Left" Margin="150,152,0,0" VerticalAlignment="Top" Width="119" Height="35"/>
    <GroupBox x:Name="groupBox" Header="Output" HorizontalAlignment="Left" Height="169" Margin="10,192,0,0" VerticalAlignment="Top" Width="394">
        <TextBox x:Name="textBox" HorizontalAlignment="Left" Height="147" Margin="0,0,-1.143,-0.714" TextWrapping="Wrap" VerticalAlignment="Top" Width="384"/>
    </GroupBox>

</Grid>

现在根据我的理解,我必须通过删除 x 和 x:Class="WpfApplication1.MainWindow" 字符串来修改此代码,并将以下内容添加到末尾;

Now from what I have understood I have to modify this code by removing the x's and the x:Class="WpfApplication1.MainWindow" string and add the following to the end;

#Read XAML
    $reader=(New-Object System.Xml.XmlNodeReader $xaml) 
    try{$Form=[Windows.Markup.XamlReader]::Load( $reader )}
    catch{Write-Host "Unable to load Windows.Markup.XamlReader. Some possible causes for this problem include: .NET Framework is missing PowerShell must be launched with PowerShell -sta, invalid XAML code was encountered."; exit}
    #===========================================================================
    # Store Form Objects In PowerShell
    #===========================================================================
    $xaml.SelectNodes("//*[@Name]") | %{Set-Variable -Name ($_.Name) -Value $Form.FindName($_.Name)}
    #===========================================================================
    # Shows the form
    #===========================================================================
    $Form.ShowDialog() | out-null

我从这里有点卡住了,尽管假设我上面的内容是正确的.我如何将这一切与 Gui 联系起来?

I am a little stuck from here though assuming what I have out above is correct. How do I tie all this to the Gui?

图形用户界面

有两个单选按钮,根据选择了哪一个,我希望运行不同的脚本,并将 Powershell 输出显示在底部的文本框中,但我该如何实现?

There are two Radio buttons and depending which one is selected I want a different script to run and the Powershell output to be displayed in the text box at the bottom but how can I accomplish this?

我想在第 1 步运行的 Powershell

The Powershell I want to run on Step 1

$credentials = get-credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri URL -Credential $credentials –AllowRedirection
Import-PSSession $Session
set-ADServerSettings -ViewEntireForest $true
Enable-RemoteMailbox -Identity test@test.com -RemoteRoutingAddress test@test.com.onmicrosoft.com
Enable-RemoteMailbox -Identity test@test.com -Archive

步骤 2

$msolcred = get-credential
connect-msolservice -credential $msolcred
Set-MsolUser -UserPrincipalName test@test.com -UsageLocation GB
$LicOpt = New-MsolLicenseOptions -AccountSkuId company:STANDARDPACK -DisabledPlans MCOSTANDARD
Set-MsolUserLicense -UserPrincipalName test@test.com -AddLicenses company:STANDARDPACK -LicenseOptions $LicOpt
Remove-PSSession $Session

谢谢大家的建议.

推荐答案

你的 $Form 应该是一个 Window 对象,因此支持它的所有方法,所以要对某些事件您必须读取控件的状态.

Your $Form should be a Window object and thus support all its methods, so to react to certain events you have to read the state of the controls.

由于这是基于脚本的,我只会命名所有相关部分并使用 FindName(您的脚本显然已经为所有命名控件创建了 powershell 变量).然后,您可以访问诸如 IsChecked 之类的属性来区分选择了哪个 RadioButton.要收听按钮点击,您可能需要 Register-ObjectEvent.当您使用 ShowDialog 时,您有一个阻塞调用,当 DialogResult 已设置,因此您应该在事件侦听器中进行设置.

As this is script based, i would just name all the relevant parts and search for them using FindName (your script apparently already creates powershell variables for all named controls). You then can access the properties like IsChecked to differentiate which RadioButton is selected. To listen to a button click you probably need Register-ObjectEvent. As you use ShowDialog you have a blocking call that returns when the DialogResult is set, so you should set that in your event listener.

我刚刚尝试了一下,这里有一个显示基本过程的小示例.

I just played around with this and here's a small sample that shows the basic process.

ScriptWindow.xaml

ScriptWindow.xaml

<Window x:Name="Title"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <StackPanel>
        <ListBox x:Name="selection" SelectionMode="Single">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <RadioButton IsChecked="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ListBoxItem}}"
                                 Content="{Binding}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <sys:String>Step 1</sys:String>
            <sys:String>Step 2</sys:String>
        </ListBox>
        <Button x:Name="run">Run</Button>
        <GroupBox Header="Output">
            <TextBox x:Name="output" IsReadOnly="True"/>
        </GroupBox>
    </StackPanel>
</Window>

ScriptWindow.ps1

ScriptWindow.ps1

Add-Type –assemblyName PresentationFramework
Add-Type –assemblyName PresentationCore
Add-Type –assemblyName WindowsBase

$xaml="ScriptWindow.xaml"
$xmlReader=(New-Object System.Xml.XmlTextReader $xaml)
$app=(New-Object System.Windows.Application)
$form=[Windows.Markup.XamlReader]::Load( $xmlReader )
$doc=(New-Object System.Xml.XmlDocument)
$doc.Load($xaml)
$run = $form.FindName("run")
$selection = $form.FindName("selection")
$output = $form.FindName("output")
$run.Add_Click({ $output.Text = $selection.SelectedItem })
$app.Run($form)

显然你也可以通过 Add_* 添加事件监听器,Register-ObjectEvent 对我不起作用.在回调中,我只是将所选选项分配给 TextBox,您需要对所选值进行大小写区分并执行各自的操作.

Apparently you can also add event listeners via Add_*, Register-ObjectEvent did not work for me. In the callback i just assign the selected option to the TextBox, you will want to do a case distinction on the selected value and execute your respective actions.

这篇关于XAML GUI 到带有变量的 Powershell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆