Powershell 从变量获取服务
我需要用户输入Powershell 从变量获取服务,powershell,variables,Powershell,Variables,我需要用户输入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 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
问题是它无法获得服务
给我这个输出:
Status Name DisplayName
------ ---- -----------
Running dhcp DHCP Client
我正在获取此错误:
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
获取服务:找不到任何服务名称为“dhcp,后台处理程序”的服务。
第5行字符:1
+获取服务-名称$Service\u名称
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+CategoryInfo:ObjectNotFound:(dhcp,后台处理程序:字符串)[获取服务],ServiceCommandException
+FullyQualifiedErrorId:NoServiceFoundCredenName,Microsoft.PowerShell.Commands.GetServiceCommand没有名称为dhcp、后台处理程序的服务。显然,您正在尝试获取服务列表(即
dhcp
和spooler
)。为此,您必须将$Service\u name
定义为实际列表,而不是带有逗号分隔单词的单个字符串:
$Service_name = "dhcp", "spooler"
如果要检索多个服务,必须将数组传递给
Get-Service
cmdlet。您可以使用-split
将字符串拆分为一个数组并修剪任何空格:
Get-Service -Name ($Service_name -split ',' | % { $_.Trim() } )
“dhcp,后台处理程序”是一个文本字符串。所以,当您将其传递给get service时,get service会查找一个名为dhcp的服务,即假脱机程序。相反,传递一个由逗号分隔的字符串“列表”。i、 e.“dhcp”、“后台处理程序”
然后你可以想传递多少就传递多少。
如果要从文本文件中收集名称,请确保每个服务都位于新行上
$Service_name = "dhcp", "spooler"
Get-Service -Name ($Service_name -split ',' | % { $_.Trim() } )