Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Invoke-Expression to call a function or script with variables?

I get the an invalid path error with this script:

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

This is 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"

Error I am getting:

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
like image 929
Gopi Avatar asked Aug 21 '17 18:08

Gopi


1 Answers

Invoke-Expression is almost always the wrong tool for whatever job you have at hand. Also, it looks to me like you actually want to run the script on the remote host. However, your Invoke-Expression statement is reading the script from the remote share and executing it locally.

Change

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

into

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

to run the script on the remote host XXXXXXXXXX.

If you do want to run the script locally connect the share \\XXXXXXXXXX\L$ as a network drive L: and call the script from that drive:

New-PSDrive -Name 'L' -PSProvider FileSystem -Root '\\XXXXXXXXXX\L$' -Persist
& 'L:\Gopi_Prod_App\ToZipNew.ps1' $buildZIP
Remove-PSDrive -Name 'L'
like image 125
Ansgar Wiechers Avatar answered Oct 02 '22 19:10

Ansgar Wiechers