2013-07-12 59 views
2

我的powershell腳本如下。我嘗試在遠程機器上壓縮文件夾。我不想在ScriptBlock內部放置Zip函數,因爲它將用於腳本的其他部分。從遠程腳本塊調用函數

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,它給錯誤$函數:拉鍊線:

+ $功能:郵編$ APPPATH $ backupFile
+ ~~~~~~~~ 意外表達式或語句中的標記'$ appPath'。

回答

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

0

我會找到讓您的共享功能集成到你的服務器的一些方法。我們在我們部署通用代碼的所有服務器上都有標準份額。當我們遠程運行代碼時,該代碼可以引用和使用共享代碼。