如何将现有PowerShell用户信息查询脚本改造为带循环菜单的交互式脚本
Got it, let's merge your existing PowerShell logic into that interactive menu framework you want. The key is to break down your original script into reusable functions, handle user ID input upfront, and create a loop that keeps the menu alive until the user quits or switches users. Here's the full working solution, with explanations along the way:
Step-by-Step Breakdown
1. Define Reusable Functions
First, we'll turn your original query logic into separate functions so we can call them easily from the menu:
Get-UserGeneralInfo: Pulls core AD user propertiesGet-UserPasswordInfo: Fetches account/password status detailsGet-UserComputerInfo: Retrieves linked PC name and boot time from your CSV/system info
2. Handle Initial User ID Input
We'll first prompt the user for a valid AD user ID, with basic validation to make sure the user exists before proceeding.
3. Create the Menu Loop
Once a valid user is selected, we'll show the menu repeatedly. Users can choose to view different info categories, switch to another user, or quit entirely.
Full Working Script
# Load Active Directory module (ensure RSAT AD tools are installed) Import-Module ActiveDirectory -ErrorAction Stop # Import user-to-PC mapping CSV once at startup $userPCMap = Import-CSV 'C:\Users\w0vlnd\Desktop\Powershells\Computers in a specific workgroup or domain.csv' #region Core Functions function Get-UserGeneralInfo { param([string]$Username) $ADprops = @('DisplayName', 'Mail', 'LastBadPasswordAttempt', 'AccountExpirationDate', 'PasswordLastSet', 'Enabled') Get-ADUser -Identity $Username -Properties $ADprops | Select-Object DisplayName, Mail, LastBadPasswordAttempt, AccountExpirationDate, PasswordLastSet, Enabled } function Get-UserPasswordInfo { param([string]$Username) $accountDetails = net user $Username /domain | Select-String -Pattern 'Account active|Password Changeable|Password Expires|Last logon' | ForEach-Object { ($_ -split '\s{2,}')[1] } [PSCustomObject]@{ 'Account Active' = $accountDetails[0] 'Password Changeable' = $accountDetails[1] 'Password Expires' = $accountDetails[2] 'Last Logon' = $accountDetails[3] } } function Get-UserComputerInfo { param([string]$Username) $pcName = $userPCMap.Where({ $_."User ID" -match $Username })."PC Name" if (-not $pcName) { Write-Warning "No PC found for user $Username in the CSV." return } try { $bootTime = SystemInfo /s $pcName | Select-String -Pattern 'System Boot Time' | ForEach-Object { ($_ -split '\s{2,}')[1] } [PSCustomObject]@{ 'PC Name' = $pcName 'System Boot Time' = $bootTime } } catch { Write-Warning "Failed to retrieve boot time for $pcName : $_" } } #endregion #region Main Interactive Flow function Show-Menu { param([string]$Title = 'UserInfo V3.1') Clear-Host Write-Host "================ $Title ================" Write-Host "Current User: *$global:currentUser*" Write-Host "Press 'U' for general user info." Write-Host "Press 'P' for account and password information." Write-Host "Press 'C' for computer information." Write-Host "Press 'G' for group memberships (add your logic here)." Write-Host "Press 'R' to search for another user ID." Write-Host "Press 'Q' to Quit." } # Function to validate and retrieve a valid AD user ID function Get-ValidUserId { do { $inputUser = Read-Host "Enter the user ID" try { $null = Get-ADUser -Identity $inputUser -ErrorAction Stop return $inputUser } catch { Write-Host "Error: User '$inputUser' not found in AD. Please try again." -ForegroundColor Red } } while ($true) } # Initialize current user with a valid ID $global:currentUser = Get-ValidUserId # Main menu loop do { Show-Menu $selection = Read-Host "Please make a selection" switch ($selection.ToUpper()) { 'U' { Write-Host "`n--- General User Info ---`n" Get-UserGeneralInfo -Username $currentUser Read-Host "`nPress Enter to return to menu" } 'P' { Write-Host "`n--- Account & Password Info ---`n" Get-UserPasswordInfo -Username $currentUser Read-Host "`nPress Enter to return to menu" } 'C' { Write-Host "`n--- Computer Info ---`n" Get-UserComputerInfo -Username $currentUser Read-Host "`nPress Enter to return to menu" } 'G' { Write-Host "`n--- Group Memberships ---`n" # Add your group membership logic here, example: # Get-ADPrincipalGroupMembership -Identity $currentUser | Select-Object Name Write-Host "Group membership logic not yet implemented - add your code here!" -ForegroundColor Yellow Read-Host "`nPress Enter to return to menu" } 'R' { $global:currentUser = Get-ValidUserId } 'Q' { Write-Host "Exiting tool... Goodbye!" -ForegroundColor Green exit } default { Write-Host "Invalid selection! Please choose a valid option." -ForegroundColor Red Read-Host "Press Enter to return to menu" } } } while ($true) #endregion
Key Improvements & Notes
- Modular Functions: Breaking logic into functions makes the script easier to maintain and update later.
- Validation: The
Get-ValidUserIdfunction ensures the user exists in AD before proceeding, reducing errors. - Error Handling: Added try/catch for computer info retrieval and warnings for missing data.
- Persistent User Context: The script keeps track of the current user, so you don't have to re-enter it every time you switch menu options.
- Extensibility: The 'G' option is ready for you to add your group membership query logic (just uncomment and modify the example line).
内容的提问来源于stack exchange,提问作者Toon




