我正在尝试运行以下代码以在OU中搜索无效的用户帐户。看来我正在使用的变量类型可能无法与参数一起使用。看起来正确吗?如果可以,我应该使用哪种类型的变量?
$scope = "-UsersOnly"
$accounts = Search-ADAccount -SearchBase "OU=Users,OU=testLab02,DC=test,DC=local" -AccountInactive -TimeSpan ([timespan]7D) $scope
foreach($account in $accounts){
If ($noDisable -notcontains $account.Name) {
Write-Host $account
#Disable-ADAccount -Identity $account.DistinguishedName -Verbose $whatIf | Export-Csv $logFile
}
}
我收到以下错误:
Search-ADAccount:找不到接受参数'-UsersOnly'的位置参数。 在C:\ Users \ Administrator \ Documents \ Disable-ADAccounts.ps1:63 char:21 + ... $ accounts = Search-ADAccount -SearchBase $ OU.DistinguishedName -Accou ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~ + CategoryInfo:InvalidArgument:(:) [Search-ADAccount],ParameterBindingException + FullyQualifiedErrorId:PositionalParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.SearchADAccount
但是,如果我不带变量地手动运行命令,它将按预期工作:
Search-ADAccount -SearchBase "OU=Users,OU=testLab02,DC=test,DC=local" -AccountInactive -TimeSpan ([timespan]7D) -UsersOnly
答案 0 :(得分:3)
$scope = "-UsersOnly"
您不能以这种方式传递存储在变量中的(开关)参数-它总是被视为(位置)参数,这说明了你看到的错误;如果直接通过 传递参数,则仅将未加引号的文字标记(例如-UsersOnly
)识别为参数名称。
您可以使用splatting
通过变量传递参数,这对您来说意味着:
# Define a hash table of parameter values.
# This hash table encodes switch parameter -UsersOnly
$scope = @{ UsersOnly = $true } # [switch] parameters are represented as Booleans
# Note the use of sigil @ instead of $ to achieve splatting
Search-ADAccount @scope -SearchBase "OU=Users,OU=testLab02,DC=test,DC=local" -AccountInactive -TimeSpan ([timespan]7D)
$scope
被定义为hash table
(@{ ... }
),其条目表示参数名称/值对。
-UsersOnly
(必须在没有 -
符号的情况下定义进入键)... $true
,对于[switch]
(标志)参数,它等于 passing 参数; $false
通常 [1] 等同于省略。要将散列表$scope
表示的参数值通过splatting
传递给命令,必须使用符号@
而不是$
,即{{ 1}}。
[1]从技术上说,命令可以区分被忽略的开关和被传递值@scope
的开关,有时还会导致不同的行为,特别是常见的$false
参数,其中-Confirm
覆盖 -Confirm:$false
首选项变量。