2

My powershell script is as below. I try to zip a folder at remote machine. I don't want to put Zip function inside ScriptBlock because it will be used in other parts of the script.

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

In $backupScript, it is giving error in $function:Zip line:

+ $function:Zip $appPath $backupFile
+ ~~~~~~~~ Unexpected token '$appPath' in expression or statement.

Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
Ant
  • 3,369
  • 5
  • 25
  • 23

2 Answers2

2

You have to refer to arguments in a scriptblock like:

$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

Also, the function will not be known by the target machine, you'll have to define it within the script-block or pass it to the machine.

Here is an example: How do I include a locally defined function when using PowerShell's Invoke-Command for remoting?

This example puts it in your perspective: PowerShell ScriptBlock and multiple functions

Community
  • 1
  • 1
RB84
  • 331
  • 4
  • 15
0

I would find some way of getting your shared functions onto your server. We have a standard share on all our servers where we deploy common code. When we run code remotely, that code can then reference and use the shared code.

Aaron Jensen
  • 25,861
  • 15
  • 82
  • 91