我想出了一个有用的脚本来帮助监视和控制远程服务器上的服务:
do {
$srv = Read-Host 'What is your ServerName?'
$srvs = Read-Host 'What is ServiceName?'
$userMenuChoice = Read-Host -Prompt "
`n1. ServiceList
`n2. Service Status.
`n3. Stop Service.
`n4. Start Service.
`n5. Exit
`nPlease Select Operation"
switch($userMenuChoice){
1{Get-Service -ComputerName $srv | select -property name,starttype}
2{gsv -cn $srv -Name "$srvs*" | Out-String}
3{Get-Service -Name "$srvs*" -ComputerName $srv | Stop-Service}
4{Get-Service -Name "$srvs*" -ComputerName $srv | Start-Service}
5{exit}
}
} while ( $userMenuChoice -ne 4 )
请帮我弄清楚如何获得提示,以保持相同的服务器和服务(或不保持)并继续使用相同的菜单。 像这样:在进入MENU $ userMenuChoice之前,它将询问我是否要保留相同的服务器Y / N(Y默认)是否要保留相同的服务Y / N(Y Default)...
在继续下一个菜单之前,我如何清除屏幕。 谢谢!
答案 0 :(得分:1)
这称为Scope
。
在该区块中创建的Variables
仅能在该区块的迭代中幸存。
$A = "Hello"
While(1 -eq 1){
$B = Read-Host 'Type Name?'
"$A $B"
}
$A
将永远是Hello,因为它是在While范围之外
$B
将永远改变,因为它在While范围内。
(这也是因为每次您将$ B都替换为读取主机时调用)
您要做的是在ServerName上提供一个选项,并将变量放置在while范围之外。
$CurrentServer = $Null
$CurrentService = $Null
do {
if(!($CurrentServer) -or $(Read-Host 'Change Server (Y,N)?') -eq "Y"){
$CurrentServer = Read-Host 'What is your ServerName?'
}
if(!($CurrentService) -or $(Read-Host 'Change Service (Y,N)?') -eq "Y"){
$CurrentService = Read-Host 'What is ServiceName?'
}
$userMenuChoice = Read-Host -Prompt @"
1. ServiceList
2. Service Status.
3. Stop Service.
4. Start Service.
5. Exit
Please Select Operation
"@
switch($userMenuChoice){
1{Get-Service -ComputerName $CurrentServer | select -property name,starttype}
2{gsv -cn $CurrentServer -Name "$CurrentService*" | Out-String}
3{Get-Service -Name "$CurrentService*" -ComputerName $CurrentServer | Stop-Service}
4{Get-Service -Name "$CurrentService*" -ComputerName $CurrentServer | Start-Service}
5{exit}
}
} while ( $userMenuChoice -ne 4 )
行
if(!($CurrentServer) -or $(Read-Host 'Change Server (Y,N)?') -eq "Y"){}
允许您在需要时更改服务器和服务,但也可以在需要时跳过它。
这是说$CurrentServer
是否为空,或者$CurrentServer
的值为Ask Change Server,如果Change Server为Y,则运行if
答案 1 :(得分:0)
这似乎太简单了。将Read-Host
cmdlet放在循环外部。
$srv = Read-Host 'What is your ServerName?'
$srvs = Read-Host 'What is ServiceName?'
do {
$userMenuChoice = Read-Host -Prompt "
`n1. ServiceList
`n2. Service Status.
`n3. Stop Service.
`n4. Start Service.
`n5. Exit
`nPlease Select Operation"
switch($userMenuChoice){
1{Get-Service -ComputerName $srv | select -property name,starttype}
2{gsv -cn $srv -Name "$srvs*" | Out-String}
3{Get-Service -Name "$srvs*" -ComputerName $srv | Stop-Service}
4{Get-Service -Name "$srvs*" -ComputerName $srv | Start-Service}
5{exit}
}
} while ( $userMenuChoice -ne 4 )