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

标签 powershell parameters active-directory powershell-5.0

我正在尝试运行以下代码来搜索 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
        }
    }

我收到以下错误:

enter image description here

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

enter image description here

最佳答案

$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 (必须在没有 - 符号的情况下定义输入键) ...
  • ... 值(value) $true ,对于 [switch] (flag) 参数相当于传递参数; $false通常[1] 相当于省略它。
  • 传递散列表表示的参数值$scope通过 splatting 发送命令, 印记 @而不是 $必须使用,即 @scope在这种情况下。


  • [1] 命令可以在技术上区分开关被省略和它被传递的值 $false ,有时会导致不同的行为,尤其是常见的 -Confirm参数,其中 -Confirm:$false覆盖 $ConfirmPreference偏好变量。

    关于powershell - 参数的变量类型问题? - 电源外壳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60292360/

    相关文章:

    oracle - Powershell中$ command.ExecuteReader()的进度条

    c# - 使用C#记录错误

    powershell - aws-cli (powershell) import-image 缺少必需参数 disk-images

    jquery - 在不重新加载页面的情况下删除 url 参数

    active-directory - 将对象类定义导入到 Active Directory (AD LDS)

    c# - Powershell Import-Module 命令不适用于 c# api

    function - 有人可以解释一下这个简单的函数是如何工作的吗

    mysql - 制作具有多个参数的mysql程序

    c# - 如何获取 AD 用户的间接组? - C#

    c# - 返回用户所属的所有 Active Directory 应用程序组的列表