Ошибка выражения с нулевым значением в скрипте Powershell с GUI Runspace - PullRequest
0 голосов
/ 27 апреля 2020

У меня есть скрипт конфигурации в powershell, который я пытаюсь женить на ВПП GUI. После нескольких неудачных попыток с кодом и gui в том же потоке я читал несколько страниц о запуске GUI в его собственном пространстве выполнения. Ниже приведен код, который я собрал.

Форма запускается, но я получаю эту ошибку, связанную с нажатием кнопки, которую я пытаюсь использовать, чтобы скрыть / показать сетки.

Вы не может вызвать метод для выражения с нулевым значением В C: \ Projects \ AVP C Setup \ Working Files \ MT Trial 3.ps1: 218 char: 18 + $ syncHa sh .fullConfig.Add_Click ({+ ~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo: InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId: InvokeMethodOnNull

С формой эти переменные видны в syncHa sh, поэтому я не уверен, что мне не хватает.

$Global:syncHash = [hashtable]::Synchronized(@{})
$newRunspace =[runspacefactory]::CreateRunspace()
$newRunspace.ApartmentState = "STA"
$newRunspace.Name = "Config GUI"
$newRunspace.ThreadOptions = "ReuseThread"
$newRunspace.Open()
$newRunspace.SessionStateProxy.SetVariable("syncHash",$syncHash)

$psCmd = [PowerShell]::Create().AddScript({
    [xml]$xaml = @"
<Window x:Class="psguiconfig.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:psguiconfig"
        mc:Ignorable="d"
        Title="Config" Height="175" Width="500">
        <Grid x:Name="mainGrid" HorizontalAlignment="Left" Height="144" Margin="0,1,0,0" VerticalAlignment="Top" Width="490">

            <Grid x:Name="choiceGrid" HorizontalAlignment="Left" Height="144" Margin="0,1,0,0" VerticalAlignment="Top" Width="490"  Visibility="Visible">

                <Label Content="Choose Config Type"  HorizontalAlignment="Center" Height="26" Margin="0,0,0,60" VerticalAlignment="Center" FontWeight="SemiBold"/>

                <Button x:Name="fullConfig" Content="Full" HorizontalAlignment="Center" Margin="0,45,250,0" VerticalAlignment="Center" Width="75"/>
                <Button x:Name="stepConfig" Content="Step By Step" HorizontalAlignment="Center" Margin="0,45,0,0" VerticalAlignment="Center" Width="75"/>
                <Button x:Name="upgradeConfig" Content="Upgrade" HorizontalAlignment="Center" Margin="250,45,0,0" VerticalAlignment="Center" Width="75" IsEnabled="False"/>

            </Grid>


            <Grid x:Name="fullGrid" HorizontalAlignment="Left" Height="144" Margin="0,1,0,0" VerticalAlignment="Top" Width="490" Visibility="Hidden">

                <Label x:Name="fullLabel" Content="Full Config"  HorizontalAlignment="Center" Height="26" Margin="0,0,0,60" VerticalAlignment="Center" FontWeight="SemiBold"/>
                <ProgressBar x:Name="fullProgress" HorizontalAlignment="Center" Height="20" Margin="0,40,0,0" VerticalAlignment="Center" Width="400"/>
                <Label x:Name="fullProgressLabel" Content="Tasking Stuffs"  Foreground="#FFFFFF" HorizontalAlignment="Center" Height="20" Margin="45,82,245,42" VerticalAlignment="Center" FontWeight="SemiBold" FontSize="7" Width="200"/>
                <Label x:Name="fullProgressPercentageLabel" Content="0%"    Foreground="#FFFFFF" HorizontalContentAlignment="Right" Height="20" Margin="419,82,45,42" VerticalAlignment="Center" FontWeight="SemiBold" FontSize="7" Width="26"/>


            </Grid>


        </Grid>

</Window>
"@

    $AttributesToRemove = @(
        'x:Class',
        'mc:Ignorable'
    )

    foreach ($Attrib in $AttributesToRemove) {
        if ( $xaml.Window.GetAttribute($Attrib) ) {
             $xaml.Window.RemoveAttribute($Attrib)
        }
    }

    $reader=(New-Object System.Xml.XmlNodeReader $xaml)

    $syncHash.Window=[Windows.Markup.XamlReader]::Load( $reader )

    [xml]$XAML = $xaml
        $xaml.SelectNodes("//*[@*[contains(translate(name(.),'n','N'),'Name')]]") | %{
        #Find all of the form types and add them as members to the synchash
        $syncHash.Add($_.Name,$syncHash.Window.FindName($_.Name) )

    }

    $syncHash.Window.ShowDialog() | Out-Null
    $syncHash.Error = $Error
})


$psCmd.Runspace = $newRunspace
$data = $psCmd.BeginInvoke()

Function Update-Window {

    Param (
        $Control,
        $Property,
        $Value,
        [switch]$AppendContent

    )

    If ($Property -eq "Close") {

        $syncHash.Window.Dispatcher.invoke([action]{$syncHash.Window.Close()},"Normal")
        Return

    }

    $syncHash.$Control.Dispatcher.Invoke([action]{

        If ($PSBoundParameters['AppendContent']) { $syncHash.$Control.AppendText($Value) } Else { $syncHash.$Control.$Property = $Value }

        }, "Normal")

}   


$syncHash.fullConfig.Add_Click({

    Update-Window -Control choiceGrid -Property Visibility -Value Hidden                                                       
    Update-Window -Control fullGrid -Property Visibility -Value Visible     

})
...