2016-01-14 75 views
3

我想爲Get-Service用戶輸入,但不接受我的變量獲得-服務從可變

我想運行下面的命令:

#### --- Content -- ### 
# - Location ## 
$Service_text = "$env:userprofile\documents\PS-Script-Services\Services.txt" 

#- Test path 
$service_test = Test-Path $Service_text 

#-- Get-content ##- 
$Get_the_service = Get-Content $service_text 

#-loop-# -- Get-Service -- ## 
if ($service_test -eq $false) { 
    Write-Host "To view your Services go to Start --> en typ services, or go to Powershell and type get-service" 
    Write-Host "Which Services do you want to monitor? (Example: Teamviewer, BITS, DHCP, Eventlog, Spooler." -BackgroundColor Black -ForegroundColor Yellow 
    Write-Host "This script only works when a service has been stopped" -BackgroundColor Black -ForegroundColor Yellow 
    Read-Host "Enter services" | Out-File $service_text 
    $ask_service = Get-Service -Name $Get_the_service 

的問題是,它不能獲得服務。

$Service_name = "dhcp" 

Get-Service -Name $service_name 

給了我這樣的輸出:

Status Name    DisplayName 
------ ----    ----------- 
Running dhcp    DHCP Client

但是如果我想多業務

$Service_name = "dhcp, spooler" 

Get-Service -Name $service_name 

我收到此錯誤:

Get-Service : Cannot find any service with service name 'dhcp, spooler'. 
At line:5 char:1 
+ Get-Service -Name $service_name 
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
    + CategoryInfo   : ObjectNotFound: (dhcp, spooler:String) [Get-Service], ServiceCommandException 
    + FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand

回答

1

存在無服務名字dhcp, spooler。顯然你試圖獲得服務列表(即dhcpspooler)。對於您必須定義$Service_name作爲一個實際的列表,而不是作爲一個字符串處理用逗號分隔的單詞:

$Service_name = "dhcp", "spooler" 
0

你,如果你想檢索多個服務到一個數組傳遞給Get-Service cmdlet的。你可以使用-split你的字符串分割成一個數組,並修剪任何空格:

Get-Service -Name ($Service_name -split ',' | % { $_.Trim() }) 
0

「DHCP,後臺處理程序」是一個字符串。因此,當您將它傳遞給get-service時,Get-Service將尋找名爲dhcp,假脫機程序的服務。相反,將它傳遞給由逗號分隔的字符串「列表」。即'dhcp','spooler' 然後你可以隨心所欲地傳遞它。 如果您要從文本文件中收集名稱,請確保每個服務都在一個新行中