【发布时间】:2023-04-02 12:36:01
【问题描述】:
我正在尝试使用 Invoke-Command 登录到远程服务器并设置一个位置路径并执行一些命令。我正在从 powershell 中的配置 xml 中读取数据。 我的 xml 属于以下类型
<?xml version="1.0"?>
<Config>
<Action Name="Deploy">
<CommandPath>C:\Program Files\Microsoft Sql server\110\</CommandPath>
<DeploymentServer>
<Server Name = 'Server1'></Server>
<Server Name = 'Server2'></Server>
</DeploymentServer>
<Deployscript1 Name = 'listservices' > </Deployscript1>
<Deployscript2 Name = 'script2' > </Deployscript2>
</Action>
<Action Name="Update">
//few more nodes
</Action>
</Config>
我已经尝试过下面的 powershell。
Set-ExecutionPolicy RemoteSigned
function RunConfiguration()
{
# get an array of 'Action' XmlElements
$actionNodes = (Select-Xml -Path $configFile -XPath '//Action').Node
do {
$Answer = Read-Host -Prompt "Select required action '$($actionNodes.Name -join "', '")'"
} Until ($Answer -in ($actionNodes.Name))
$selectedNode = $actionNodes | Where-Object {$_.Name -eq $Answer}
Write-Host $selectedNode.Name
$selectedNode.DeploymentServer.Server | ForEach-Object {
$ServerName = $_.Name
Write-Host $ServerName
if($selectedNode.Name -ieq "deploy")
{
$ScriptCode = $selectedNode.Deployscript1.Name
$ScriptCode2 = $selectedNode.Deployscript2.Name
}
Write-Host $ScriptCode
Write-Host $selectedNode.CommandPath
Invoke-Command -ComputerName $ServerName -ScriptBlock {
$Configuration = $args[0]
Set-Location $selectedNode.CommandPath
#Execute first command
& $ScriptCode
#Execute second command
$ScriptCode2
} -ArgumentList $SelectedAnswer
}
}
$spAdminServiceName = "SPAdminV4"
$currentDir=(split-path $myinvocation.mycommand.path -parent)
$configFile = $currentDir
$configFile += "\DeployConfig.xml"
Execute-Commands $configFile
RunConfiguration
Write-Host -f White "Press Enter key to exit..."
Read-Host
我收到以下 2 个错误: 错误 1:无法处理参数,因为参数“路径”的值为空。将参数“path”的值更改为非空值。
错误 2:管道元素中“&”之后的表达式生成的对象无效。它必须产生一个命令名称、一个脚本块或一个 CommandInfo 对象。
我能够在写入主机的 xml 中获得正确的路径。如何解决这两个错误? 谢谢
更新的代码 1:我可以毫无问题地从 XML 中获取值。
Invoke-Command -ComputerName $ServerName -ScriptBlock {
$Configuration = $args[0]
#Navigate to location
Set-Location $scriptPath.ToString()
#Execute first command
& $ScriptCode
#Execute second command
$ScriptCode1
} -ArgumentList $SelectedAnswer
【问题讨论】:
标签: powershell