【问题标题】:How do I get DatePicker and TextBox information from XAML into a Powershell variable?如何将 DatePicker 和 TextBox 信息从 XAML 获取到 Powershell 变量中?
【发布时间】:2016-07-22 14:48:43
【问题描述】:

我是脚本新手(第一年),这是我第一次尝试从 VisualStudio 获取 WPF 应用程序并将其 XAML 代码转换为我可以与 Powershell 一起使用的东西。我正在尝试创建一个小型应用程序,它允许我在 TextBox 字段中输入 Active Directory 用户名并从 DatePicker 对象中选择一个日期,然后将这两条信息都转换为 Powershell 变量。从那里,我为 AD 用户启用 VPN 访问,然后将日期用作“截止日期”,此时我将禁用用户的访问。这两个变量也将输出到我们服务器上的一个 .csv 文件,该文件将由计划任务每​​天读取。如果截止日期与当天匹配,则会触发另一个脚本来禁用用户的 VPN 访问。 (那个预定的powershell脚本不在此列,后面会写。)

请查看我的代码并帮助我弄清楚为什么我无法从 TextBox 和 DatePicker 检索信息来填充我的 Powershell 变量!我的问题似乎在“实际上使对象工作”部分。我收到“WPFtextbox_Username.Text”和“DatePicker.SelectedDate.Value.Date.ToShortDateString”在 Powershell 中无效的错误,因此当我写入 .csv 文件时变量 $ADUser 和 $ExpirationDate 为空。此脚本菜鸟将不胜感激任何帮助!

感谢 https://foxdeploy.com/2015/04/16/part-ii-deploying-powershell-guis-in-minutes-using-visual-studio/ 提供此 XAML 到 Powershell 代码的框架。

$inputXML = @"
<Window x:Name="AllowVPNWindow" x:Class="AddADUserToVPN.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:AddADUserToVPN"
    mc:Ignorable="d"
    Title="Add VPN Access" Height="365.779" Width="577.356">
  <Grid>
    <Grid.Background>
        <LinearGradientBrush EndPoint="0.5,1"     MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
            <GradientStop Color="Black" Offset="1"/>
            <GradientStop Color="#FF781515" Offset="0.077"/>
        </LinearGradientBrush>
    </Grid.Background>
    <Label x:Name="label_username" Content="Username:" HorizontalAlignment="Left" Height="39" Margin="19,20,0,0" VerticalAlignment="Top" Width="95" Foreground="White" FontWeight="Bold" FontSize="16"/>
    <Label x:Name="label_VPNCutoffDate" Content="VPN Access Cutoff Date:" HorizontalAlignment="Left" Height="63" Margin="19,80,0,0" VerticalAlignment="Top" Width="204" Foreground="White" FontWeight="Bold" FontSize="16" />
    <TextBox x:Name="textBox_Username" HorizontalAlignment="Left" Height="22" Margin="25,52,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="125"/>
    <Button x:Name="button_AddUser" Content="Add User" HorizontalAlignment="Left" Height="37" Margin="445,37,0,0" VerticalAlignment="Top" Width="80" FontSize="16">
        <Button.Effect>
            <DropShadowEffect/>
        </Button.Effect>
    </Button>
    <TextBlock x:Name="textBlock_Instructions" HorizontalAlignment="Left" Height="84" Margin="299,215,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="244" Foreground="White" FontSize="16"><Run Text="Enter a "/><Run Foreground="#FF26D636" Text="valid"/><Run Text=" Active Directory username and select the date that the user's VPN access will "/><Run Foreground="#FF26D636" Text="end"/><Run Text=". "/></TextBlock>
    <DatePicker x:Name="DatePicker" HorizontalAlignment="Left" Height="34" Margin="25,116,0,0" VerticalAlignment="Top" Width="125" FontSize="16"/>
  </Grid>
</Window>
"@        

$inputXML = $inputXML -replace 'mc:Ignorable="d"','' -replace "x:N",'N'  -replace '^<Win.*', '<Window'


[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
[xml]$XAML = $inputXML
#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. Double-check syntax and ensure .net is installed."}

#===========================================================================
# Store Form Objects In PowerShell
#===========================================================================

$xaml.SelectNodes("//*[@Name]") | %{Set-Variable -Name "WPF$($_.Name)" -Value $Form.FindName($_.Name)}

Function Get-FormVariables{
if ($global:ReadmeDisplay -ne $true){Write-host "If you need to reference this display again, run Get-FormVariables" -ForegroundColor Yellow;$global:ReadmeDisplay=$true}
write-host "Found the following interactable elements from our form" -ForegroundColor Cyan
get-variable WPF*
}

Get-FormVariables

#===========================================================================
# Actually make the objects work
#===========================================================================

##### Grab information from the Text Box and from the DatePicker objects


function Get-FormFields {
$ADUser = if (WPFtextbox_Username.Text -ne $null){$ADUser = WPFtextbox_Username.Text}

            else{$wshell = New-Object -ComObject Wscript.Shell
                 $wshell.Popup("Enter valid username.",0,"Try Again")
                 &Rest}


$ExpirationDate = (DatePicker.SelectedDate.Value.Date.ToShortDateString)
}





$WPFbutton_AddUser.Add_Click({
    #Resolve Form Settings
    Get-FormFields

    ##### Add VPN permission to the selected user
    Set-ADUser $ADUser -Replace @{msnpallowdialin=$true} 



    ##### Append ADUsername and Expiration Date to .csv file
    "$ADUser, $ExpirationDate" | out-file -FilePath \\10.48.0.200\d$\adusertest.txt -append -width 200


$Form.Close()})


#===========================================================================
# Shows the form
#===========================================================================
write-host "To show the form, run the following" -ForegroundColor Cyan

function Show-Form{
$Form.ShowDialog() | out-null

}

Show-Form

【问题讨论】:

  • 看起来您在调用 Get-FormFields 函数中获取所选日期时缺少一个美元符号 ($)。 $ExpirationDate = ($DatePicker.SelectedDate.Value.Date.ToShortDateString)。 WPFtextbox_Username.Text 的实例相同

标签: wpf xaml powershell datepicker textbox


【解决方案1】:

发现其他一些看起来没有写在代码中的内容,例如方法调用中缺少括号 (),变量中缺少更多美元符号 ($),以及日期选择器的名称输入错误(应该是 WPFDatepicker) .我在下面运行了更新的代码,它在文本文件中产生了预期的结果。

$inputXML = @"
<Window x:Name="AllowVPNWindow" x:Class="AddADUserToVPN.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:AddADUserToVPN"
    mc:Ignorable="d"
    Title="Add VPN Access" Height="365.779" Width="577.356">
  <Grid>
    <Grid.Background>
        <LinearGradientBrush EndPoint="0.5,1"     MappingMode="RelativeToBoundingBox" StartPoint="0.5,0">
            <GradientStop Color="Black" Offset="1"/>
            <GradientStop Color="#FF781515" Offset="0.077"/>
        </LinearGradientBrush>
    </Grid.Background>
    <Label x:Name="label_username" Content="Username:" HorizontalAlignment="Left" Height="39" Margin="19,20,0,0" VerticalAlignment="Top" Width="95" Foreground="White" FontWeight="Bold" FontSize="16"/>
    <Label x:Name="label_VPNCutoffDate" Content="VPN Access Cutoff Date:" HorizontalAlignment="Left" Height="63" Margin="19,80,0,0" VerticalAlignment="Top" Width="204" Foreground="White" FontWeight="Bold" FontSize="16" />
    <TextBox x:Name="textBox_Username" HorizontalAlignment="Left" Height="22" Margin="25,52,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="125"/>
    <Button x:Name="button_AddUser" Content="Add User" HorizontalAlignment="Left" Height="37" Margin="445,37,0,0" VerticalAlignment="Top" Width="80" FontSize="16">
        <Button.Effect>
            <DropShadowEffect/>
        </Button.Effect>
    </Button>
    <TextBlock x:Name="textBlock_Instructions" HorizontalAlignment="Left" Height="84" Margin="299,215,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="244" Foreground="White" FontSize="16"><Run Text="Enter a "/><Run Foreground="#FF26D636" Text="valid"/><Run Text=" Active Directory username and select the date that the user's VPN access will "/><Run Foreground="#FF26D636" Text="end"/><Run Text=". "/></TextBlock>
    <DatePicker x:Name="DatePicker" HorizontalAlignment="Left" Height="34" Margin="25,116,0,0" VerticalAlignment="Top" Width="125" FontSize="16"/>
  </Grid>
</Window>
"@        

$inputXML = $inputXML -replace 'mc:Ignorable="d"','' -replace "x:N",'N'  -replace '^<Win.*', '<Window'


[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
[xml]$XAML = $inputXML
#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. Double-check syntax and ensure .net is installed."}

#===========================================================================
# Store Form Objects In PowerShell
#===========================================================================

$xaml.SelectNodes("//*[@Name]") | %{Set-Variable -Name "WPF$($_.Name)" -Value $Form.FindName($_.Name)}

Function Get-FormVariables{
    if ($global:ReadmeDisplay -ne $true){
        Write-host "If you need to reference this display again, run Get-FormVariables" -ForegroundColor Yellow
        $global:ReadmeDisplay=$true
    }
    write-host "Found the following interactable elements from our form" -ForegroundColor Cyan
    get-variable WPF*
}

Get-FormVariables

#===========================================================================
# Actually make the objects work
#===========================================================================

##### Grab information from the Text Box and from the DatePicker objects

function Get-FormFields {
    $Script:ADUser = if ($WPFtextbox_Username.Text -ne $null){
        $WPFtextbox_Username.Text
    }

    else{
        $wshell = New-Object -ComObject Wscript.Shell
        $wshell.Popup("Enter valid username.",0,"Try Again")
    }


    $Script:ExpirationDate = $WPFDatePicker.SelectedDate.ToShortDateString()
}

$WPFbutton_AddUser.Add_Click({
    #Resolve Form Settings
    Get-FormFields

    ##### Add VPN permission to the selected user
    #Set-ADUser $ADUser -Replace @{msnpallowdialin=$true} 



    ##### Append ADUsername and Expiration Date to .csv file
    "$ADUser, $ExpirationDate" | out-file -FilePath adusertest.txt -append -width 200


$Form.Close()})


#===========================================================================
# Shows the form
#===========================================================================
write-host "To show the form, run the following" -ForegroundColor Cyan

function Show-Form{
$Form.ShowDialog() | out-null

}

Show-Form

【讨论】:

  • 感谢 TON 帮我解决这个问题,boeprox。就像我说的那样,我刚刚涉足这个脚本游戏,所以我非常感谢对这个脚本的帮助。缺少的括号在哪里?太爱了!
  • @CoreyCutler 缺少括号的方法是 ToShortDateString
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-21
相关资源
最近更新 更多