如何在 powershell CLI 中传递函数参数?

如何在 powershell CLI 中传递函数参数?

我正在尝试在 powershell CLI 中将参数传递给下面的函数:

 function FuncCheckService{

 param($ServiceName)
 $arrService = Get-Service -Name $ServiceName
 if ($arrService.Status -ne "Running"){
 Start-Service $ServiceName
 Write-Host "Starting " $ServiceName " service" 
 " ---------------------- " 
 " Service is now started"
 }

 if ($arrService.Status -eq "running"){ 
 Write-Host "$ServiceName service is already started"
 }
 }

服务功能脚本

使用软件保护服务(sppsvc)和 Powershell CLI 上的以下命令进行了以下方式测试:

PS 用户>.\CHECKSERVICE.PS1 FuncCheckService -ServiceName 'sppsvc'

仍然无法工作,没有输出。我是否犯了上述任何错误?

提前致谢

答案1

使用一项服务调用函数:

function FuncCheckService{

param($ServiceName)
$arrService = Get-Service -Name $ServiceName
if ($arrService.Status -ne "Running"){
Start-Service $ServiceName
Write-Host "Starting " $ServiceName " service"
" ---------------------- "
" Service is now started"
}



if ($arrService.Status -eq "running"){
Write-Host "$ServiceName service is already started"
}

}
FuncCheckService(sppsvc)

输出:

.\service.ps1
Start-Service : Não é possível validar o argumento no parâmetro 'InputObject'. O argumento é nulo ou vazio. Forneça um
argumento que não seja nulo ou vazio e tente o comando novamente.
No C:\Users\Marlon\OneDrive\uteis\service.ps1:8 caractere:15
+ Start-Service $ServiceName
+               ~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Start-Service], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.StartServiceCommand

Starting    service
 ----------------------
 Service is now started
 service is already started

相关内容