如何将XAML中的DatePicker和TextBox信息转换为Powershell变量?

时间:2016-07-22 14:48:44

标签: wpf xaml powershell datepicker textbox

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

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

感谢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

1 个答案:

答案 0 :(得分:0)

发现其他一些看起来没有写入代码的东西,例如方法调用中缺少括号(),变量中缺少美元符号($)以及日期选择器的错误名称(应该是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