我正在编写一个脚本,该脚本将检查用户是否是管理员,如果不是,它将当场添加它们,注销,然后我可以重新登录以进行测试。这是我遇到问题的部分:
$Cred = Get-Credential ("$env:COMPUTERNAME\Administrator")
$Group = [ADSI]("WinNT://"+$env:COMPUTERNAME+"/Administrators,Group")
$User = $env:USERNAME
$Domain = $env:USERDOMAIN
Invoke-Command -Computername localhost -Cred $Cred -ScriptBlock {$Group.add("WinNT://$Domain/$User,user")}
每次我运行这个我都会收到以下错误:
You cannot call a method on a null-valued expression.
有什么想法可以解决这个问题吗?
工作解决方案:
$Cred = Get-Credential ("$env:COMPUTERNAME\Administrator")
$User = $env:USERNAME
$Domain = $env:USERDOMAIN
Invoke-Command -Computername localhost -Cred $Cred -ScriptBlock {
param ($User, $Domain, $ComputerName)
$Group = [ADSI]("WinNT://$ComputerName/Administrators,Group")
$Group.add("WinNT://$Domain/$User,user")
} -ArgumentList $User, $Domain, $ENV:COMPUTERNAME