表达式或语句中的意外标记 - powershell

时间:2017-10-06 17:10:53

标签: powershell powershell-v2.0 powershell-v3.0 powershell-remoting

## To run the script
# .\get_status.ps1 -Hostname <host> -Service_Action <action> -Service_Name <name>

#$Hostname = "hostname"
#$Service_Action = "Get-Service"
#$Service_Name = "service_name"

param(
    [string]$Hostname,
    [string]$Service_Action,
    [string]$Service_Name
)

$ScriptBlockContent = {
    param($Service_Action, $Service_Name)
    & $Service_Action $Service_Name
    }

# user credentials
$Username = "username"
$Password = "password"

# To avoid Manual entry of Username and Password
$Secure_String = convertto-securestring $Password -asplaintext -force
$User_cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $Username, $Secure_String

# Create a Session
$pso = New-PSSessionOption -NoMachineProfile
$sess = New-PSSession -ComputerName $Hostname -SessionOption $pso -credential $User_cred

#Run a powershell script in the session.
Invoke-Command -Session $sess -ScriptBlock $ScriptBlockContent -ArgumentList $Service_Action, $Service_Name

# Remove session
Remove-PSSession $sess

运行脚本:

.\<script_name>.ps1 -Hostname <host> -Service_Action <action> -Service_Name <name>

例如:服务行动是 - 获取服务,停止服务,启动服务 然后命名

Command: Get-Service Servicename

我收到错误: 这行代码中表达式或语句中出现意外的标记:

$ScriptBlockContent = {
        param($Service_Action, $Service_Name)
        $Service_Action $Service_Name # here is the error
        }

2 个答案:

答案 0 :(得分:0)

teacher::dosomething(bar)

答案 1 :(得分:-1)

您将命令作为字符串传递给函数,因此您在语法上对$Service_Action $Service_Name执行的操作是在一行中引用两个字符串对象,而不需要任何操作符连接它们。这就是例外的原因。

告诉powershell,你想要将一个字符串作为命令执行,你有几个选择:

一种选择是将命令作为单个字符串传递给Invoke-Expression cmdlet:

Invoke-Expression "$Service_Action $Service_Name"

或者你可以使用call-Operator &,它也告诉powershell将命令视为字符串。在这种情况下,您不能在单个字符串中提供cmdlet和参数,而是在两个中:

& $Service_Action $Service_Name