PowerShell自定义改密函数Set-UserPassword无法接收管道输入求助
问题根源
你编写的Set-UserPassword函数里,ComputerName参数没有开启按管道属性名绑定的特性,只有User、NewPassword参数加了ValueFromPipelineByPropertyName = $true配置,所以管道传入的自定义对象的ComputerName属性无法自动绑定到对应参数上,导致调用缺失必选参数无法正常运行。
修复方案
只需要给Set-UserPassword的ComputerName参数也加上ValueFromPipelineByPropertyName = $true配置即可,修改后的函数完整代码如下:
function Set-UserPassword { [CmdletBinding()] param ( [Parameter(Mandatory = $true, Position = 0, ValueFromPipelineByPropertyName = $true)] # 新增此配置项 [string]$ComputerName, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, Position = 1)] [string]$User, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, Position = 2)] [string]$NewPassword, [Parameter(Position = 3,ValueFromPipelineByPropertyName = $true)] [string]$PasswordVersion ) PROCESS { if ($env:COMPUTERNAME -eq $ComputerName) { Set-UserPasswordLocaly $User $NewPassword } else { Set-UserPasswordRemotely $ComputerName $User $NewPassword } } }
调用优化
修复后可以省去手动循环的写法,直接用管道批量调用,代码更简洁:
$x = @( [pscustomobject]@{ ComputerName = 'smzmi0027d' User = 'localadmin' NewPassword = 'djkufdjkuf1234' }, [pscustomobject]@{ ComputerName = 'smzmi0027d' User = 'localadmin' NewPassword = '1' } ) # 直接管道传入即可执行,无需手动遍历 $x | Set-UserPassword | Out-GridView
内容的提问来源于stack exchange,提问作者user2978216
相关产品推荐
相关产品推荐

