参数的变量类型问题? - 电源外壳

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: (:) [搜索-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"

您不能以这种方式传递存储在变量中的(开关)参数 - 它总是会被视为(位置)参数,解释了你看到的错误;对于直接传递的参数,只有不带引号的文字标记如-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(输入键必须定义没有 - sigil)...
      • ... 值为 $true,对于 [switch](标志)参数等同于 传递 参数; $false 通常 [1] 相当于 省略 它。
  • 要通过 splatting 将哈希表 $scope 表示的参数值传递给命令,必须使用印记 @ 而不是 $,即,在这种情况下 @scope


[1] 一个命令可以在技术上区分一个开关被 省略 和它被传递值 $false,有时结果在不同的行为中,特别是使用常见的 -Confirm 参数,其中 -Confirm:$false 覆盖 $ConfirmPreference 偏好变量。