[英]Variable Type Issue For Parameter? - Powershell
我正在尝试运行以下代码来搜索 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
$scope = "-UsersOnly"
您不能以这种方式传递存储在变量中的 (switch)参数- 它总是会被视为 (positional) argument ,这解释了您看到的错误; 对于直接传递的参数,只有不带引号的文字标记(例如-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
(必须在没有-
-UsersOnly
的情况下定义输入键)...$true
,对于[switch]
(flag) 参数相当于传递参数; $false
通常[1]相当于省略它。 通过由散列表所表示的参数值$scope
经由到命令splatting
,印记@
代替$
必须使用的,即, @scope
在这种情况下。
[1] 命令可以从技术上区分被省略的开关和它以$false
值传递,有时会导致不同的行为,特别是使用通用的-Confirm
参数,其中-Confirm:$false
覆盖$ConfirmPreference
首选项多变的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.