Powershell日期GUI奇怪的行为

时间:2017-04-19 19:33:09

标签: powershell

当我运行此代码时,您会看到第一个写主机将显示今天的日期,但最后2个将显示默认日期。有谁知道为什么?

代码来自微软,所以我很困惑为什么它不会工作? https://technet.microsoft.com/en-us/library/ff730942.aspx

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 

[DateTime] $dtmDate = New-Object DateTime;
[string] $dt = "";
$objForm = New-Object Windows.Forms.Form 

$objForm.Text = "Select a Date, then press the enter key" 
$objForm.Size = New-Object Drawing.Size @(350,190) 
$objForm.StartPosition = "CenterScreen"

$objForm.KeyPreview = $True


$objForm.Add_KeyDown({
    if ($_.KeyCode -eq "Enter") 
        {
            $dtmDate = $objCalendar.SelectionStart
            #$dt = $objCalendar.SelectionStart.ToShortDateString();
            Write-Host $dtmDate;
            $objForm.Close()
        }
    })

$objForm.Add_KeyDown({
    if ($_.KeyCode -eq "Escape") 
        {
            $objForm.Close()
        }
    })

$objCalendar = New-Object System.Windows.Forms.MonthCalendar 
$objCalendar.ShowTodayCircle = $False
$objCalendar.MaxSelectionCount = 1
$objForm.Controls.Add($objCalendar) 

$objForm.Topmost = $True

$objForm.Add_Shown({$objForm.Activate()})  
[void] $objForm.ShowDialog() 

Write-Host "Date selected: $dtmDate"
if ($dtmDate)
    {
        Write-Host "Date selected: $dtmDate"
    }

1 个答案:

答案 0 :(得分:0)

$dtmDate更改为$global:dtmDate

原因是您在触发事件时分配值,因此仅在本地声明和初始化。在事件之外,仅声明变量。通过使用$global,如果变量适用于所有脚本,则更改范围。

顺便说一下。永远不要相信Microsoft文档