【问题标题】:Powershell: Do not refresh Get-Date stored in variable [duplicate]Powershell:不要刷新存储在变量中的Get-Date [重复]
【发布时间】:2020-07-02 22:09:57
【问题描述】:

这可能很简单,但我想不通。

我正在获取系统日期并将其存储到一个变量中,然后在单击按钮的当天执行负 1。问题是,cmdlet 在每次单击时都会刷新,并且不会继续递减。所以如果今天是 21 号,按钮点击会输出 20,然后如果我再次点击它应该输出 19,但它总是输出 20。

[int] $myDD = (Get-Date -Format dd)

button1_click= { 
     $myDD = $myDD - 1
     write-host $myDD
}

完整代码

[int] $myDD = (Get-Date -Format dd)

function Create-Form {

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
$form1 = New-Object System.Windows.Forms.Form
$button4 = New-Object System.Windows.Forms.Button 

#################################
#             CLICKS            #
#################################
$button4_Click= {
    $myDD = $myDD - 1
    write-host $myDD
}

$OnLoadForm_StateCorrection={
    $form1.WindowState = $InitialFormWindowState
}

#################################
#             FORM              #
#################################
$form1.Text = "Test"
$form1.Name = "form1"
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 280
$System_Drawing_Size.Height = 100
$form1.ClientSize = $System_Drawing_Size

#################################
#            BUTTONS            #
#################################

#button4
$button4.TabIndex = 4
$button4.Name = "button4"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 20
$System_Drawing_Size.Height = 15
$button4.Size = $System_Drawing_Size
$button4.UseVisualStyleBackColor = $True
$button4.Text = "<<"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 245
$System_Drawing_Point.Y = 10
$button4.Location = $System_Drawing_Point
$button4.DataBindings.DefaultDataSourceUpdateMode = 0
$button4.Font = New-Object System.Drawing.Font("Lucida Console",12)
$button4.TextAlign.ContentAlignment.TopLeft
$button4.add_Click($button4_Click)
$form1.Controls.Add($button4)

<#-------------------------------#>

$InitialFormWindowState = $form1.WindowState
$form1.add_Load($OnLoadForm_StateCorrection)
$form1.ShowDialog()| Out-Null

}
Create-Form

【问题讨论】:

  • 简而言之:$myDD 是在 script 范围内创建的;事件处理程序代码在 child scope 中运行,它可以使用$myDD get 脚本级变量,但 setting $myDD 创建一个新的本地变量,如linked answer 中所述。此处接受的答案通过 $script: 范围说明符显示了正确的解决方案。

标签: powershell variables scope


【解决方案1】:

在展示完你的完整代码后,看起来你可以这样做了:

button1_click= {
     $script:myDD--
     write-host $myDD
}

Script 范围内递减变量。您可以查看about_scopes 了解更多信息。

注意:这里的最佳实践是使用$script:myDD--脚本 级别范围,因为该变量是在正在运行的脚本的范围内定义的。即使在脚本运行之后,使用 全局 作用域也会产生挥之不去的副作用,因此在使用此作用域级别时要小心。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    相关资源
    最近更新 更多