我正在尝试在PowerShell中编写代码,该代码将一直循环直到用户想要退出。因此,允许委派用户更改学生帐户的密码。
我已经测试了密码更改的代码,该代码可以正常工作。
一旦我尝试添加一个while循环,代码就不会运行。
#Open powershell as Administrator
Start-process Powershell -verb RunAs
# Connect to the Domain Controller
$session = New-PSSession -ComputerName "" -Credential (Get-Credential)
Invoke-Command $session -Scriptblock { Import-Module ActiveDirectory }
Import-PSSession -session $session -Module ActiveDirectory
#verify that you're connectedto the Domain
Get-ADDomainController -Filter * | Select-Object name
#run Password Change
$userid = Read-Host -Prompt 'Please enter the studnets login ID'
$newPassword = Read-Host -Prompt 'Please enter the studnets new password'
$run = 'yes'
while ($run -eq 'yes')
{
if (Get-ADUser -Filter {SamAccountName -eq $userid})
{
Set-ADAccountPassword $userid -Reset -NewPassword (ConvertTo-SecureString -Force -AsPlainText '$newPassword')
Write - Host "$userid` password has now been changed to: $newPassword"
}
else
{
Write - Host "$userid` does not exist, please try again."
}
$answer = Read-Host -Prompt 'Would you like to change another studnets password? [y|n]'
while ($answer -notcontains 'n' -or $answer -notcontains 'N' -or $answer -notcontains 'y' -or $answer -notcontains 'Y')
{
$answer = Read-Host -Prompt 'Please answer [y|n]'
}
if ($answer -eq 'y' -or $answer -eq 'Y')
{
$run = 'yes'
}
if ($answer-eq 'n' -or $answer -eq 'N')
{
exit
}
}
答案 0 :(得分:1)
PowerShell默认/设计不区分大小写。因此,无需检查。
根据您的追求,您可能对该项目进行了过度设计。
我建议将其更改为简单的Do..Until。
Clear-Host
do
{
"`n"
$TargetUser = Read-Host -Prompt 'Enter a user SamAccountName'
"Processing user $TargetUser"
Get-ADUser -Identity $TargetUser
"`n"
$answer = Read-Host -Prompt 'Would you like to see another user? [y|n]'
}
until ($answer -eq 'n')
"You entered $answer. Finished processing routine."
Enter a user SamAccountName: Administrator
Process user Administrator
...
Enabled : True
GivenName :
Name : Administrator
...
SamAccountName : Administrator
...
Would you like to see another user? [y|n]: y
Enter a user SamAccountName: sqladmin
Process user sqladmin
...
Enabled : True
GivenName : SqlAdmin
Name : SqlAdmin ServiceAccount
...
SamAccountName : sqladmin
...
Would you like to see another user? [y|n]: n
You entered n. Finished processing routine.
就我个人而言,如果我这样做,我会以不同的方式处理。
因此消除了所有手动提示工作。