如何使用wpf复选框和PowerShell将变量内容放入

问题描述:

我试图在选中复选框时将IP放在变量中,并将该变量用作Invoke-SQLCMD中的IP地址。 无论我做什么,似乎$ DB00的内容都是空的。如何使用wpf复选框和PowerShell将变量内容放入

$window.DB00.add_Checked({ 

    $DB00 = '192.168.1.1' 
    [System.Object]$sender = $args[0] 
    [System.Windows.RoutedEventArgs]$e = $args[1] 

}) 

$window.DB00.add_Unchecked({ 

    $DB00 = $null 
    #Get-ChildItem variable:\DB00 
    #Remove-Item variable:\DB00 
    [System.Object]$sender = $args[0] 
    [System.Windows.RoutedEventArgs]$e = $args[1] 

}) 

$window.DB00.add_Indeterminate({ 

    $DB00 = $null 
    [System.Object]$sender = $args[0] 
    [System.Windows.RoutedEventArgs]$e = $args[1] 

}) 

#Collect Input fields# 
$window.Button.add_Click({ 

    $UserName = $window.UserName.Text.ToString() 
    $PassWord = $window.PassWord.Text.ToString() 
    $ServerAddress = $DB00 
    $DataBase = $window.DataBase.Text.ToString() 
    $SQLQuery = $window.Query.Text.ToString() 
    Invoke-Sqlcmd -AbortOnError ` 
     -Username $UserName ` 
     -Password $PassWord ` 
     -Database $DataBase ` 
     -Query $SQLQuery ` 
     -QueryTimeout 30 ` 
     -ServerInstance $ServerAddress | 
     Out-GridView -Title $DataBase 
    [System.Object]$sender = $args[0] 
    [System.Windows.RoutedEventArgs]$e = $args[1] 

}) 

这是一个scoping问题。当调用add_Checked()代码时,它将在子范围内运行,这意味着在脚本块内对$DB00所做的更改不会影响$DB00以外的值。

为了说明这一点,尝试运行下面的代码片段:

$DB00 = 123 
&{ 
    $DB00 = 456 
    &{ 
    $DB00 = 789 
    } 
} 
# What do you think will be printed? 
Write-Host $DB00 

如果这是一个脚本或功能的一部分,你可以用“脚本”范围名称来限定变量:

$script:DB00 = '192.168.1.1' 

您还可以使用*-Variable cmdlet与-Scope参数。这允许您指定相对父范围当前范围:

$DB00 = 123 
&{ 
    Set-Variable DB00 -Value 456 -Scope 1 
    &{ 
    $DB00 = 789 
    } 
} 
# What do you think will be printed now? :) 
Write-Host $DB00 
+0

非常,非常漂亮的把:) – sodawillow

+0

喜马蒂亚斯,这对我的解决方案,非常感谢你! – AbNadi

+0

[PS C:\ Users \ master>写主机$ DB00 456]尼斯,你可以计算出来自不同范围的相同变量:) – AbNadi