我想将一个叫做$dec
的变量赋值为null,但是它报错了。这是我的代码:
import-module activedirectory
$domain = "domain.example.com"
$dec = null
Get-ADComputer -Filter {Description -eq $dec}
我想将一个叫做$dec
的变量赋值为null,但是它报错了。这是我的代码:
import-module activedirectory
$domain = "domain.example.com"
$dec = null
Get-ADComputer -Filter {Description -eq $dec}
$null
,$true
,$false
等。$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 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.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
If you pipe the
$null
variable to theForEach-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
As a result, you cannot use
$null
to mean "no parameter value." A parameter value of$null
overrides the default parameter value.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++ }
output:
Appointment on Tuesday: Meeting Appointment on Friday: Team lunch
使用 $dec = $null
根据文档:
$null是一个自动变量,包含NULL或空值。您可以在命令和脚本中使用此变量来表示缺少或未定义的值。
PowerShell将$null视为具有值的对象,即作为显式占位符,因此您可以使用$null来表示一系列值中的空值。
正如其他人所说,使用$null
。
然而,处理$null
并不简单。
在列表(或更准确地说,System.Array
对象)中,当索引列表时,$null
被视为一个占位对象,因此($null, $null).count
输出2
。
但是在其他情况下,$null
被视为一个标志,表示没有内容(没有对象;或更准确地说,是一个“空值表达式”,由.GetType()
报告),因此($null).count
输出0
。
因此
$null.count; # Output = 0
($null).count; # Output = 0
(, $null).count; # Output = 1
($null, $null).count; # Output = 2
($null, $null, $null).count; # Output = 3
.count
和.length
返回相同的输出结果。$aaa = $null; $aaa.count
$bbb = ($null, $null); $bbb.count
这段代码分别输出 0
和 2
。
同样地,如果使用 ForEach
循环,如下所示:
$aaa = $null; ForEach ($a in $aaa) {write-host "Foo" -NoNewLine}
$bbb = ($null, $null); ForEach ($b in $bbb) {write-host "Bar" -NoNewLine}
这段代码会分别输出nothing和BarBar
。
需要注意的是,在操作从列表返回的单个项目时,$null
再次被视为“空值表达式”,可以通过运行来确认。
$xxx = ($null, "foo", $null); ForEach ($x in $xxx) {write-host "C=" $x.count "| " -NoNewLine}
该代码输出 C= 0 | C= 1 | C= 0 |
。
import-module activedirectory
$domain = "domain.example.com"
Get-ADComputer -Filter '*' -Properties Description | where { $_.Description -eq $null }
$null
,会出现哪些错误? - Kev