这个 PowerShell 脚本有什么问题?(尝试远程创建用户名和设置)

这个 PowerShell 脚本有什么问题?(尝试远程创建用户名和设置)

我有以下 PowerShell 脚本,但它似乎不起作用,当到达第 21 行(否则)时它似乎会引发错误。

$Username = "asdfasdfasdf"
$Password = "asdfasdfasdfasdf"

$group = "Administrators"

$adsi = [ADSI]"WinNT://$env:COMPUTERNAME"
$existing = $adsi.Children | where {$_.SchemaClassName -eq 'user' -and $_.Name -eq $Username }

if ($existing -eq $null) {

    Write-Host "Creating new local user $Username."
    & NET USER $Username $Password /add /y /expires:never

   Write-Host "Adding local user $Username to $group."
   & NET LOCALGROUP $group $Username /add

}
else {
    Write-Host "Setting password for existing local user $Username."
    $existing.SetPassword($Password)
}

 Write-Host "Ensuring password for $Username never expires."
 & WMIC USERACCOUNT WHERE "Name='$Username'" SET PasswordExpires=FALSE

错误信息:

else : The term 'else' is not recognized as the name of a cmdlet, function, 
script file, or operable program. Check
the spelling of the name, or if a path was included, verify that the path is 
correct and try again.
At line:1 char:1
+ else {
+ ~~~~
+ CategoryInfo          : ObjectNotFound: (else:String) [], 
CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

答案1

事实证明,问题是由于在 PowerShell 中使用右键单击粘贴导致的,因此每次只能运行一行。通过一次性运行所有内容(例如作为脚本、PowerShell ISE,或者在执行之前简单地使用 Ctrl+V 粘贴),它就可以正常工作。感谢大家的帮助。

答案2

逐行或逐节执行脚本有时可能会导致不良后果。

Else除非在与语句相同的实例中执行,否则语句无效if

如果分段执行脚本,则必须包含所有ifelseelseif语句(如果它们存在于您尝试执行的段中)。

相关内容