如何调用-Expression来调用带变量的函数或脚本?

时间:2017-08-21 18:22:39

标签: powershell powershell-remoting

我在这个脚本中遇到了无效的路径错误:

$buildZIP= 'starmatic'
echo $buildZIP
$command = ”\\XXXXXXXXXX\L$\Gopi_Prod_App\ToZipNew.ps1 $buildZIP”
Invoke-Expression -Command $command

这是ToZipNew.ps1

Param(
    [Parameter(Position=1, Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string]$build
)
echo "$build"
$S = "L:\Gopi_Prod_App\$build\App_Data\*"
$D = "\Gopi_Prod_App\Starmatic_UI.zip"

echo $S
echo $D

Get-ChildItem "$S" | Compress-Archive -DestinationPath "$D" -Verbose
#Compress-Archive -Path "$S" -CompressionLevel Fastest -DestinationPath "$D"

我收到错误:

Compress-Archive : The path 'L:\Gopi_Prod_App' either does not exist or is not a
valid file system path.  
At \\XXXXXXXXXXX\L$\Gopi_Prod_App\ToZipNew.ps1:13 char:45 
+ ... t-ChildItem "$S" | Compress-Archive -DestinationPath "$D" -Verbose
+                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  
    + CategoryInfo          : InvalidArgument: (L:\Gopi_Prod_App:String) [Compress-Archive], InvalidOperationException  
    + FullyQualifiedErrorId : ArchiveCmdletPathNotFound,Compress-Archive

1 个答案:

答案 0 :(得分:5)

无论您手头有什么工作,

Invoke-Expression都是almost always the wrong tool。另外,在我看来,您确实希望在远程主机上运行该脚本。但是,您的Invoke-Expression语句正在从远程共享中读取脚本并在本地执行

更改

$command = ”\\XXXXXXXXXX\L$\Gopi_Prod_App\ToZipNew.ps1 $buildZIP”
Invoke-Expression -Command $command

Invoke-Command -Computer 'XXXXXXXXXX' -ScriptBlock {
    & 'L:\Gopi_Prod_App\ToZipNew.ps1' $using:buildZIP
}

在远程主机XXXXXXXXXX上运行脚本。

如果您确实要在本地运行脚本,请将共享\\XXXXXXXXXX\L$作为网络驱动器L:连接,然后从该驱动器调用脚本:

New-PSDrive -Name 'L' -PSProvider FileSystem -Root '\\XXXXXXXXXX\L$' -Persist
& 'L:\Gopi_Prod_App\ToZipNew.ps1' $buildZIP
Remove-PSDrive -Name 'L'