简体   繁体   English

POWERSHELL-获取服务中的变量-名称$ Var

[英]POWERSHELL - Variable in Get-service -Name $Var

Here my script : 这是我的脚本:

Relance de Service sur machine distante 机器维修服务代表

Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser -Force
$passwd = ConvertTo-SecureString -AsPlainText -Force -String PASSWORD #Remplacer 'Password' par votre Mot de passe Datacenter
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList "LOGIN",$passwd #Remplacer 'login' par votre login datacenter
$Server = Read-Host -Prompt 'Veuillez entrer le nom du serveur'
$session = New-PSSession -ComputerName $Server -Credential $cred
$Service = Read-Host -Prompt 'Veuillez entrer le nom du service'
Invoke-Command -Session $session -ScriptBlock {$A = get-service -Name $Service}
if ($A.Status -eq "Stopped") {$A.start()}
elseIf ($A.status -eq "Running") {Write-Host -ForegroundColor Yellow $A.name "is running"}
Get-PSSession | Remove-PSSession

My script is almost working, but i've got an 'error' or i missed something. 我的脚本几乎可以正常工作,但是我遇到了“错误”或错过了一些东西。 When i use prompt to get the server name $Server and put it in the variable everything is ok. 当我使用提示符获取服务器名称$ Server并将其放在变量中时,一切正常。 But when i use prompt to get the Service name in a variable $Service, and use get-service -name $Service, it doesn't work. 但是,当我使用提示符在变量$ Service中获取服务名称,并使用get-service -name $ Service时,它不起作用。 Why? 为什么? Could you help me please? 请问你能帮帮我吗?

Your issue is not with Get-Service but with Invoke-Command . 您的问题不是Get-Service而是Invoke-Command The variable $Service you use is not passed from your session to the invoked command. 您使用的变量$Service不会从会话传递到调用的命令。 There are multiple options to do this: 有多个选项可以执行此操作:

By param (as Paxz mentioned in comments): 通过param(如Paxz在评论中提到的):

-ScriptBlock {param($Service) $A = get-service -Name $Service} -ArgumentList $Service

By using: : 通过using:

-ScriptBlock {$A = get-service -Name $using:Service}

By argument directly: 通过直接争论:

-ScriptBlock {$A = get-service -Name $args[0]} -ArgumentList $Service

Also keep in mind the scope of variables while trying to restart them. 在尝试重新启动变量时,还请记住变量的范围。


Some useful links to check when it comes to passing variables to remote sessions: 一些有用的链接,用于检查何时将变量传递到远程会话:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM