首页 > 解决方案 > 为 PowerShell 脚本创建 UI

问题描述

我使用 .xaml 扩展格式创建了一个 UI 页面,并将其放入我设备上的本地目录中。现在我想在 PowerShell 脚本中使用该页面。

.xaml 看起来像:

<Window x:Class="PoshGUI_sample.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:PoshGUI_sample"
    mc:Ignorable="d"
    Title="Disk Information" Height="326" Width="403">
<Grid>

    <StackPanel Orientation="Horizontal" VerticalAlignment="Top" HorizontalAlignment="Center">
        <Label Content="Computer Name:" VerticalAlignment="Center" Margin="10,10, 0, 0"/>
        <TextBox Name="txtComputer" Text="" VerticalAlignment="Center" Height="23" Width="174" Margin="0, 10, 10, 0"/>
        <Button Name="btnQuery" VerticalAlignment="Center" Content="Query" Margin="5, 15, 10, 5" Height="18" Width="59"/>  
    </StackPanel>
    <TextBox HorizontalAlignment="Center" Name="txtResults" Text="" IsReadOnly="True" Margin="10,60,0,0" Height="225" Width="373"/>
</Grid>

我试过的脚本:

    Add-Type -AssemblyName PresentationFramework

Function Get-FixedDisk {
    [CmdletBinding()]
    param (
        # Parameter help description
        [Parameter(Mandatory)]
        [string]$Computer
    )

    $Diskinfo = Get-WmiObject Win32_LogicalDisk -ComputerName $Computer -Filter 'DriveType=3'
    $Diskinfo
}

#Locate XAML file
$xamlFile = "C:\Users\florian.voss\source\repos\PoshGUI-sample\PoshGUI-sample\MainWindow.xaml"

#create window
$inputXML = Get-Content $xamlFile -Raw
$inputXML = $inputXML -replace 'mc:ignorable="d"', '' -replace "x:N", 'N' -replace '^Win.*', '<Window'
[xml]$xaml = $inputXML

#Read XAML
$reader = (New-Object System.Xml.XmlNodeReader $xaml)
try {
    $window = [Windows.Markup.XamlReader]::Load( $reader )
} catch {
    Write-Warning $_.Exception
    throw
}

# Create variables based on form control names.
# Variable will be named as 'var_<control name>'

$xaml.SelectNodes("//*[@Name]") | ForEach-Object {
    #"trying item $($_.Name)"
    try {
        Set-Variable -Name "var_$($_.Name)" -Value $window.FindName($_.Name) -ErrorAction Stop
    } catch {
        throw 
    }
}
Get-Variable var_*

$Null = $window.ShowDialog()

我猜这个问题从脚本的第 20 行开始,并继续到以下行,即使 powershell 在第 25 行或 smth 中发现错误。我在网上找到了第 20 行,因此它可能不适用于我的 .xaml 文件。因此,我希望问题出在我尝试用脚本第 20 行替换的 .xaml 文件的第一行中。

错误截图

标签: c#powershell

解决方案


推荐阅读