Reputation: 31
i wrote a script that works perfect. The code is:
[Array] $Services = '1.service','2.serviec','3.service';
# loop through each service, if its running, stop it
foreach($ServiceName in $Services)
{
$arrService = Get-Service -Name $ServiceName
write-host $ServiceName
while ($arrService.Status -eq 'Running')
{
Stop-Service $ServiceName
write-host $arrService.status
write-host $ServiceName stopping
Start-Sleep -seconds 60
$arrService.Refresh()
if ($arrService.Status -eq 'Stopped')
{
Write-Host $ServiceName is now Stopped
}
}
}
But I need a script that ask a names service and enter in [Array] $Services = ... I tryed to add this:
$Dienst = Read-Host "Please enter the Services"
[Array] $Services = $Dienst
# loop through each service, if its running, stop it
foreach($ServiceName in $Services)
{
$arrService = Get-Service -Name $ServiceName
write-host $ServiceName
while ($arrService.Status -eq 'Running')
{
Stop-Service $ServiceName
write-host $arrService.status
write-host $ServiceName stopping
Start-Sleep -seconds 60
$arrService.Refresh()
if ($arrService.Status -eq 'Stopped')
{
Write-Host $ServiceName is now Stopped
}
}
}
When i started the script receive an error
My Question is - How i can add a different service, which powershell can find in system? Thanks a lot.
Upvotes: 2
Views: 199
Reputation: 437062
What Read-Host
returns is a single string, and if you cast a string to [Array]
you'll end up with a single-element array containing the entire string.
If what is conceptually an array (list) is contained in your string, you must construct an array from it yourself, using text parsing:
For simplicity, I suggest requiring that the input not require embedded quoting (just foo
instead of 'foo'
) - which assumes that service names don't have embedded spaces:
# Simulate Read-Host input
$servicesList = 'LAS_LMB, LAS_LWS, LAS_CORE'
# Parse the string input by the user into an array of service names.
$services = -split ($servicesList -replace ',', ' ')
Note: The above accepts ,
, whitespace, or a combination of the two as the separator between service names, combining the unary form of the -split
operator for whitespace-based splitting with the -replace
operator for replacing commas with spaces.
Note that Get-Service
's -Name
parameter directly accepts an array of names, so your processing command can be simplified to:
Get-Service -Name $services | Where-Object Status -eq Running |
ForEach-Object {
Write-Host $_.Name
do {
Stop-Service $_.Name
Write-Host $_.Status
Write-Host $_.Name stopping
Start-Sleep -seconds 60
$_.Refresh()
if ($_.Status -eq 'Stopped') {
Write-Host $_.Name is now stopped
}
} while ($_.Status -eq 'Running')
}
Upvotes: 3