Ich habe bereits vorgestellt, wie man selbst Menüs erstellen kann. Nun stelle ich vor, wie diese dynamisch generiert und als Skript (oder Funktion) aufgerufen werden können.
##############################################################
# Aufruf des Skripts bsplws. wie folgt:
##############################################################
# $Question = "Welcher Prozess soll genommen werden?"
# $Command = "Get-Process"
# $Command = 'Get-Process | ? {$_.ID -lt 1000}' # Auf Grund des Dollar-Zeichens müssen hier einfache Anführungszeichen genommen werden
# $Attributes = @("ID","ProcessName") # Wenn es mehrere Attribute sind, muss es sein Array sein!
# $ProcessName = (C:\_Skripte\Snippets\Select-FromMenue.ps1 -Question $Question -Command $Command -Attributes $Attributes).ProcessName
#
##############################################################
# Anmerkung:
# Das Skript funktioniert nur bei einer 1zu1 Zuweisung der Attribute.
# Etwas wie...:
# -> $var.Name = $Result.Server.Name
# ...funktioniert leider nicht. Dafür muss das Skript in das eigene Skript kopiert und angepasst werden.
param(
[String]$Question,
[Parameter(Mandatory=$true)][String]$Command,
[Parameter(Mandatory=$true)][Array]$Attributes
)
if(!$Question){
$Question = "Welcher Eintrag genommen werden?"
}
$Attributes = ,"Selection" + $Attributes
# Auswahlmenü erstellen
$AllResults = Invoke-Expression $Command
$InputIDMappings = @()
$i = 1
foreach($Result in $AllResults){
$InputIDMapping = "" | Select $Attributes
$InputIDMapping.Selection = $i
foreach($Attribute in $Attributes){
if($Attribute -ne "Selection"){
$InputIDMapping.$Attribute = $Result.$Attribute
}
}
$InputIDMappings += $InputIDMapping
$i++
}
# Auswahlmenü anzeigen
$Selection = $null
while($InputIDMappings.Selection -notcontains $Selection){
cls
Write-Host $Question -ForegroundColor Yellow
$Display = $InputIDMappings | Out-String
Write-Host $Display
$Selection = Read-Host "Bitte eine Auswahl treffen"
}
$Return = ($InputIDMappings | ? {$_.Selection -eq $Selection})
return $Return
Der Aufruf sieht dann z.B. wie folgt aus:
$Question = "Welcher Prozess soll genommen werden?"
$Command = 'Get-Process | ? {$_.ID -lt 1000}' # Auf Grund des Dollar-Zeichens müssen hier einfache Anführungszeichen genommen werden
$Attributes = @("ID","ProcessName") # Wenn es mehrere Attribute sind, muss es sein Array sein!
$ProcessName = (C:\_Skripte\Snippets\Select-FromMenue.ps1 -Question $Question -Command $Command -Attributes $Attributes).ProcessName
Welcher Prozess soll genommen werden?
Selection ID ProcessName
--------- -- -----------
1 932 Calculator
2 544 csrss
3 216 dwm
4 0 Idle
5 336 jusched
6 752 lsass
7 744 services
8 396 smss
9 76 svchost
10 900 svchost
11 944 svchost
12 836 SynLenovoHelper
13 4 System
14 880 WhatsApp
15 664 wininit
Bitte eine Auswahl treffen: 15
PS C:\windows\system32> $ProcessName
wininit