我正在嘗試編寫一個腳本來啓動,停止或重新啓動遠程計算機上的服務。調用cmdlet時使用變量作爲動詞
我發現這一點:
Start-Service -InputObject $(Get-Service -Computer COMPUTER1 -Name spooler)
,並開始在周圍建造我的腳本。
這是我有:
$Action = Read-Host "Start, Stop or Restart service?"
$Serv = Read-Host "Service name?"
$Comp = Read-Host "Computer name?"
"$Action"-Service -InputObject $(Get-Service -Computer "$Comp" -Name "$Serv")
當我運行此腳本,我得到這個錯誤:
At U:\Serv.ps1:4 char:10
+ "$Action"-Service -InputObject $(Get-Service -Computer "$Comp" -Name "$Serv")
+ ~~~~~~~~
Unexpected token '-Service' in expression or statement.
At U:\Serv.ps1:4 char:19
+ "$Action"-Service -InputObject $(Get-Service -Computer "$Comp" -Name "$Serv")
+ ~~~~~~~~~~~~
我已經試過這個:
$Action = Read-Host "Start, Stop or Restart service?"
$Action = $Action + "-Service"
$Serv = Read-Host "Service name?"
$Comp = Read-Host "Computer name?"
"$Action" -InputObject $(Get-Service -Computer "$Comp" -Name "$Serv")
,但我得到類似的錯誤:
At U:\Serv.ps1:5 char:11
+ "$Action" -InputObject $(Get-Service -Computer "$Comp" -Name "$Serv")
+ ~~~~~~~~~~~~
Unexpected token '-InputObject' in expression or statement.
At U:\Serv.ps1:5 char:24
+ "$Action" -InputObject $(Get-Service -Computer "$Comp" -Name "$Serv")
+ ~~
Unexpected token '$(' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : UnexpectedToken
Unexpected token '-InputObject' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : UnexpectedToken
如何將輸入 - 「開始」,「停止」或「重新啓動」傳遞給命令的動詞部分?
第一組的代碼工作完美。謝謝! 我無法得到代碼的第二部分,使用PromptForChoice()工作。我可能沒有需要的東西加載。錯誤的第一部分顯示如下: New-Object:找不到類型[Collection.ObjectModel.Collection [Management.Automation.Host.ChoiceDescription]]:驗證包含此類型的程序集 已加載。 – urtonbay
@urtonbay您正在運行哪個PowerShell版本? –
我正在運行版本4. – urtonbay