从远程脚本块调用函数

时间:2013-07-12 13:34:41

标签: powershell

我的powershell脚本如下。我尝试在远程机器上压缩文件夹。我不想将Zip函数放在ScriptBlock中,因为它将用于脚本的其他部分。

function Zip{  
    param([string]$sourceFolder, [string]$targetFile)  
    #zipping   
}  

$backupScript = {  
    param([string]$appPath,[string]$backupFile)      
    If (Test-Path $backupFile){ Remove-Item $backupFile }  
    #do other tasks      
    $function:Zip $appPath $backupFile  
}  

Invoke-Command -ComputerName $machineName -ScriptBlock $backupScript -Args $appPath,$backupFile

$backupScript中,它在$ function中给出了错误:Zip line:

  

+ $ function:Zip $ appPath $ backupFile
  + ~~~~~~~~   表达式或语句中出现意外的标记'$ appPath'。

2 个答案:

答案 0 :(得分:2)

你必须在脚本块中引用参数,如:

$backupScript = {  
    param([string]$appPath,[string]$backupFile)      
    If (Test-Path $backupFile){ Remove-Item $backupFile }  
    #do other tasks      
    $function:Zip $args[0] $args[1]  
}  
Invoke-Command -ComputerName $machineName -ScriptBlock $backupScript -Args       $appPath,$backupFile

此外,目标机器无法识别该功能,您必须在脚本块中定义它或将其传递给机器。

这是一个例子: How do I include a locally defined function when using PowerShell's Invoke-Command for remoting?

此示例将其置于您的视角中: PowerShell ScriptBlock and multiple functions

答案 1 :(得分:0)

我会找到一些方法将您的共享功能放到您的服务器上。我们在部署公共代码的所有服务器上都有标准共享。当我们远程运行代码时,该代码可以引用并使用共享代码。

相关问题