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

unexpected token in expression or statement - powershell

## 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
        }

您将命令作为字符串传递给您的函数,因此您使用 $Service_Action $Service_Name 在句法上所做的是在一行中引用两个字符串对象,而无需任何运算符连接它们。这就是异常的原因。

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

一个选项是将命令作为单个字符串传递给 Invoke-Expressioncmdlet:

Invoke-Expression "$Service_Action $Service_Name"

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

& $Service_Action $Service_Name
## 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`enter code here`