问题
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}
回答1:
These are automatic variables, like $null, $true, $false etc.
about_Automatic_Variables, see https://technet.microsoft.com/en-us/library/hh847768.aspx?f=255&MSPPError=-2147217396
$NULL
$nullis 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
$nullas 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
$nullis included in a collection, it is counted as one of the objects.C:\PS> $a = ".dir", $null, ".pdf" C:\PS> $a.count 3If you pipe the
$nullvariable to theForEach-Objectcmdlet, 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 HelloAs a result, you cannot use
$nullto mean "no parameter value." A parameter value of$nulloverrides the default parameter value.However, because Windows PowerShell treats the
$nullvariable as a placeholder, you can use it scripts like the following one, which would not work if$nullwere 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
回答2:
Use $dec = $null
From the documentation:
$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.
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.
回答3:
If the goal simply is to list all computer objects with an empty description attribute try this
import-module activedirectory
$domain = "domain.example.com"
Get-ADComputer -Filter '*' -Properties Description | where { $_.Description -eq $null }
来源:https://stackoverflow.com/questions/28697349/how-do-i-assign-a-null-value-to-a-variable-in-powershell