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
(必须在没有符号的情况下定义输入键-
)... - ... 带有 value
$true
,对于[switch]
(flag) 参数,这相当于传递参数;$false
通常[1]等同于省略它。
- 参数名称
- 这里只定义了一个参数名-值对:
要将 hashtable 表示的参数值通过 传递
$scope
给命令,必须使用splatting
sigil@
而不是,即在这种情况下。$
@scope
[1] 命令可以在技术上区分开关被省略和它被传递 value $false
,并且有时会导致不同的行为,特别是使用 common-Confirm
参数,其中-Confirm:$false
覆盖首$ConfirmPreference
选项变量。
推荐阅读
- angular - 在一个 Azure Blob 存储上托管多个 Angular 应用
- wordpress - 带有 Docker-Compose 和 AWS RDS MySQL 数据库的 AWS EC2 上的 WordPress
- airflow - 气流将 jinja 模板传递给 dag 参数
- r - ggplot:使用最小值和最大值的分类值添加 geom_rect
- windows - 无法运行 Windows docker 容器中路径中的可执行文件
- c# - 通信对象 System.ServiceModel.ChannelFactory` 不能用于通信,因为它处于故障状态
- amazon-web-services - 如何使用 serverless-offline 检测无服务器框架功能是否离线运行?
- swift - TabView 在第一次查看 SwiftUI 时不显示文本
- c# - 为什么在 for 循环的每次迭代中实例化一个新对象会覆盖以前的列表条目?
- python - 如何在熊猫的一个图形上绘制两个不同的图形?