gpt4 book ai didi

powershell - 从远程脚本 block 调用函数

转载 作者:行者123 更新时间:2023-12-02 23:47:05 25 4
gpt4 key购买 nike

我的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行中给出了错误:

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

最佳答案

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

$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?

该示例将其放在您的 Angular :
PowerShell ScriptBlock and multiple functions

关于powershell - 从远程脚本 block 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17616186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com