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.

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.