如何在 PowerShell 中为变量分配空值? [英] How do I assign a null value to a variable in PowerShell?
问题描述
我想为一个名为 $dec
的变量分配一个空值,但它给了我错误.这是我的代码:
I want to assign a null value to a variable called $dec
, but it gives me errors. Here is my code:
import-module activedirectory
$domain = "domain.example.com"
$dec = null
Get-ADComputer -Filter {Description -eq $dec}
推荐答案
这些是自动变量,比如 $null
, $true
, $false代码>等
These are automatic variables, like $null
, $true
, $false
etc.
about_Automatic_Variables
,请参阅 https://technet.microsoft.com/en-us/library/hh847768.aspx?f=255&MSPPError=-2147217396
$NULL$null
是一个包含 NULL 或空的自动变量价值.您可以使用此变量来表示不存在或未定义的命令和脚本中的值.
$NULL
$null
is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.
Windows PowerShell 将 $null
视为具有值的对象,即作为显式占位符,因此您可以使用 $null 表示空一系列值中的值.
Windows PowerShell treats $null
as an object with a value, that is, as
an explicit placeholder, so you can use $null to represent an empty
value in a series of values.
例如,当$null
被包含在一个集合中时,它被算作对象之一.
For example, when $null
is included in a collection, it is counted as
one of the objects.
C:\PS> $a = ".dir", $null, ".pdf"
C:\PS> $a.count
3
如果您将 $null
变量通过管道传输到 ForEach-Object
cmdlet,它会为 $null
生成一个值,就像它为其他对象一样.
If you pipe the $null
variable to the ForEach-Object
cmdlet, it
generates a value for $null
, just as it does for the other objects.
PS C:\ps-test> ".dir", $null, ".pdf" | Foreach {"Hello"}
Hello
Hello
Hello
因此,您不能使用 $null
来表示无参数值".一种$null
的参数值覆盖默认参数值.
As a result, you cannot use $null
to mean "no parameter value." A
parameter value of $null
overrides the default parameter value.
但是,因为 Windows PowerShell 将 $null
变量视为占位符,您可以使用它的脚本如下所示,其中如果 $null
被忽略,将无法工作.
However, because Windows PowerShell treats the $null
variable as a
placeholder, you can use it scripts like the following one, which
would not work if $null
were ignored.
$calendar = @($null, $null, "Meeting", $null, $null, "Team Lunch", $null)
$days = Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"
$currentDay = 0
foreach($day in $calendar)
{
if($day –ne $null)
{
"Appointment on $($days[$currentDay]): $day"
}
$currentDay++
}
输出:
Appointment on Tuesday: Meeting
Appointment on Friday: Team lunch
这篇关于如何在 PowerShell 中为变量分配空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!