PowerShell GetFilteredUsers函数异常:Get-ADUser Filter参数为空报错
问题
编写了一个从指定OU检索符合筛选条件的AD用户的PowerShell函数,代码如下:
$OU = "OU=Users,DC=internal,DC=contoso,DC=com" $Filter = "Department -eq 'HR'" $FilePath = "C:\Scripts\Output.log" $Timestamp = Get-Date -Format "yyyy-MM-dd hh:mm" # Function description function GetFilteredUsers { param ( [string]$OU, [string]$Filter ) $FilteredUsers = Get-ADUser -Filter $Filter -SearchBase $OU if ($FilteredUsers.Count -eq 0) { "$Timestamp : No users in $OU matching filter $Filter" | Out-File -FilePath $FilePath -Append } else {write-host 'Hooray!'} } GetFilteredUsers($OU,$Filter)
运行代码时出现错误:
Get-ADUser : Cannot validate argument on parameter 'Filter'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again. At line:13 char:41 + $FilteredUsers = Get-ADUser -Filter $Filter -SearchBase $OU + ~~~~~~~ + CategoryInfo : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser
输出日志文件显示OU与Filter变量内容异常拼接:
2024-04-03 10:11 : No users in OU=Users,DC=internal,DC=contoso,DC=com
Department -eq 'HR' matching filter
单独执行Get-ADUser命令(无函数包裹)时运行正常,修改变量名也无法解决问题,忽略了什么?
原因分析
PowerShell中调用函数的语法错误,使用了GetFilteredUsers($OU,$Filter)这种类C#的括号传参方式,这会把$OU和$Filter打包成一个数组作为第一个参数传递给函数,导致:
- 函数的
$OU参数接收了数组[OU值, Filter值],日志输出时数组元素换行显示,造成拼接异常 - 函数的
$Filter参数没有接收到任何值,为$null,触发Get-ADUser的参数验证错误
解决方法
修改函数调用方式,使用PowerShell标准的空格分隔参数语法:
# 显式指定参数名的写法(推荐,可读性强) GetFilteredUsers -OU $OU -Filter $Filter # 或者省略参数名的位置参数写法(需保持参数顺序与函数param定义一致) GetFilteredUsers $OU $Filter
同时建议优化函数内的日志逻辑,避免$Timestamp在函数定义前就固定值(如果函数多次调用,时间戳不会更新),可以把$Timestamp移到函数内部,并将FilePath设为函数参数:
function GetFilteredUsers { param ( [string]$OU, [string]$Filter, [string]$FilePath ) $Timestamp = Get-Date -Format "yyyy-MM-dd hh:mm" $FilteredUsers = Get-ADUser -Filter $Filter -SearchBase $OU if (-not $FilteredUsers) { "$Timestamp : No users in $OU matching filter $Filter" | Out-File -FilePath $FilePath -Append } else { Write-Host 'Hooray!' } } # 调用时传递所有必要参数 GetFilteredUsers -OU $OU -Filter $Filter -FilePath $FilePath
内容的提问来源于stack exchange,提问作者RockYoClock
相关产品推荐
相关产品推荐

