powershell - 基本循环帮助 - Powershell

标签 powershell

在这里完成 Powershell Noobie。

我有一个 .bat我想转换为 Powershell 的文件。

基本上在运行时;它要求用户输入他们的 Active Directory 凭据。一经验证;它以提升的域用户身份启动 RSAT 工具(例如:dhcpmgmt.msc)。

但是,如果凭据不正确( if %ERRORLEVEL% EQU 5 );它执行 GOTO 和 echo "Incorrect username and password"然后循环返回请求用户再次输入他们的凭据。

当我使用:

do 
{
  Start-Process -FilePath C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Credential (Get-Credential "$env:USERDNSDOMAIN\")  -ArgumentList "C:\Windows\System32\dhcpmgmt.msc"
} until ($response -eq $null)

有用。但是如果我输入了错误的密码;窗口关闭。

我想要用户名/密码不正确的通知信息,然后重新引导他们再次输入他们的凭据。这将循环直到用户输入正确的凭据或简单地单击取消按钮。

非常感谢任何帮助/指导。提前致谢!

最佳答案

您可以在 while 循环中运行它以继续要求凭据,直到它们有效为止。

  • 获取凭证
  • 使用新凭据运行 powershell
  • 如果失败,请要求新的凭据。如果没有,就跳出循环。
  • while ($true) 
    {
      $userCreds = Get-Credential "$env:USERDNSDOMAIN\"
      try {
         Start-Process powershell -Credential $userCreds -ArgumentList "C:\Windows\System32\dhcpmgmt.msc" -ErrorAction Stop
         break
      }
      catch {
         Write-Output "Invalid Credentials"
         Write-Output "Enter new credentials?"
         if ((Read-Host) -ne "Yes") { break }
    
      }
    }
    

    关于powershell - 基本循环帮助 - Powershell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60172970/

    相关文章:

    powershell - 我们如何使用powershell脚本在CSV文件的顶部添加新行?

    powershell - New-SelfSignedCertificate -CertStoreLocation 找不到路径

    regex - Powershell 替换多行

    powershell - 托管PowerShell:PowerShell与Runspace与RunspacePool与管道

    azure - Az Powershell 命令不适用于 "Cloud service (classic)"

    powershell - 使用 Azure 资源管理器时如何获取 CustomScriptExtensions 的输出?

    Powershell - Streamwriter

    Powershell 数字格式

    powershell - CSV 文件生成新名称 - 调用 powershell

    powershell - 是否可以在用户 cd-ing 到目录时运行脚本