0

我正在使用控制台菜单从 AD 回收站恢复已删除的项目。

有 4 个菜单选项,每个选项都需要用户输入(读取主机),但格式必须正确,否则无法恢复。有没有办法在控制台菜单中为每个变量/读取主机定义约束?

这是我的菜单

#Keep looping and running the menu until the user selects Q (or q).
Do {
#use a Switch construct to take action depending on what menu choice
#is selected.
Switch (Show-Menu $menu " `nActive Directory Restore AD Tree Menu" -clear) {
 "1" {Write-Host " `nRestore AD Tree using LastKnownRDN" -ForegroundColor Yellow
     $RDN=Read-Host " `nEnter LastKnownRDN of deleted object (eg. STAFF) "
     .\Restore_ADTree.ps1 Restore-ADTree -lastknownRDN $RDN
     sleep -seconds 2
     } 
 "2" {Write-Host "Restore AD Tree using LastKnownRDN and LastKnownParent" -ForegroundColor Green
     $RDN=Read-Host " `nEnter LastKnownRDN of deleted object (eg. STAFF) "
     $LNP=Read-Host " `nEnter LastKnownParent of deleted object in quotes (eg. "OU=Staff,DC=xxxx,DC=xxxx,DC=xxxx,DC=xxxx")"
     .\Restore_ADTree.ps1 Restore-ADTree -lastknownRDN $RDN -lastknownParent $LNP
      sleep -seconds 5
      }
 "3" {Write-Host "Restore AD Tree Using Identity Distinguished Name" -ForegroundColor Magenta
     $DName=Read-Host " `nEnter the Distinguished Name of deleted object (eg. "OU=Test,OU=Staff,DC=xxxx,DC=xxxx,DC=xxxx,DC=xxxx") "
     .\Restore_ADTree.ps1 Restore-ADTree -identity $DName
     sleep -seconds 2
     }
 "4" {Write-Host "Restore AD Tree Using Identity GUID"
     $GUID=Read-Host " `nEnter the GUID of deleted object (eg. b48290aa-e14f-4417-9c03-560a546d18b9) "
     .\Restore_ADTree.ps1 Restore-ADTree -identity $GUID
     sleep -seconds 2    
     }
 "Q" {Write-Host "Goodbye" -ForegroundColor Cyan
     Return
     }
 Default {Write-Warning "Invalid Choice. Try again."
          sleep -milliseconds 750}
} #switch
} While ($True)

所以对于 2. 我想确保 $LNP 在引号中

对于 3. 我希望输入至少包含 DC=XXXX,DC=XXXX,DC=XXXX 并用引号引起来

对于 4. 我想确保它在 xxxxxxxx-xxxx-xxxxx-xxxxx-xxxxxxxxxxx 中没有特殊字符。

我也希望能够写到控制台,如果他们弄错了关于它需要采用什么格式的消息。

如果有人能指出我正确的方向,我将不胜感激。

谢谢,阿米莉亚

4

1 回答 1

1

您可以创建自己的Read-Host实现,如下所示:

function MyRead-Host($prompt, $regex)
{
    while(!$inputOk)    {   $inputOk = (IsInputOk (Read-Host -Prompt $prompt) $regex)   }   
}

function IsInputOk([string] $string, [string] $regex)
{
    if ($string -eq $regex) { return $true  } return $false
}

这个特定的实现将要求用户输入,直到它等于$regex变量。如果你想拥有通用功能,你应该做一些智能的正则表达式匹配,否则你可以为每个案例编写自己的验证器

于 2012-05-03T11:54:19.667 回答