数组值Powershell
我写了一个完美的剧本。代码是:数组值Powershell,powershell,Powershell,我写了一个完美的剧本。代码是: [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 whil
[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
}
}
}
但我需要一个脚本,它可以询问名称服务并输入[Array]$Services=。。。我试图补充这一点:
$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
}
}
}
当我启动脚本时,收到一个错误
我的问题是-如何添加不同的服务,powershell可以在系统中找到哪些服务?
非常感谢。返回的是单个字符串,如果您将字符串强制转换为[Array]
,您将得到一个包含整个字符串的单元素数组
如果字符串中包含概念上的数组(列表),则必须使用文本解析自己从中构造数组:
为简单起见,我建议要求输入不需要嵌入引号(只需foo
而不是'foo'
)-这假设服务名称没有嵌入空格:
注意:上面接受、
、空格或两者的组合作为服务名称之间的分隔符,将基于空格的拆分的一元形式与用空格替换逗号的组合
请注意,
Get Service
的-Name
参数直接接受名称数组,因此您的处理命令可以简化为:
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')
}
如果你的问题还没有完全回答,请考虑回答或提供反馈。
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')
}