gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:09:05 47 4
gpt4 key购买 nike

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

关于powershell - 表达式或语句中的意外标记 - powershell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46610749/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com