Invoking remote executables with Powershell

The Powershell Invoke-Command  script is very powerful for automating the deployment of software built in a Continuous Integration process. However, I just ran into a bit of new syntax when trying to invoke an executable on the remote box when specifying arguments.

Initially I was trying to call the 7z.exe using the usual DOS syntax of

"C:Program Files7-zip7z.exe" x -y $serverZipPath
This caused Powershell to error with:
Unexpected token 'x' in expression or statement.
At line:1 char:34
+ "C:Program Files7-Zip7z.exe" x <<<< -y d:temprelease.zip
+ CategoryInfo : ParserError: (x:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken 

Here’s the working Unzip Script example. It relies on 7-zip being installed on the remote machine:

# Purpose : Uncompresses the $zipFilename to $destinationPath on the target $server
# Returns : True for success
function InvokeUnzipScript($server, $cred, $serverZipPath, $serverReleasePath)
{
  Invoke-Command -ComputerName $server -Credential $cred 
    -ArgumentList $serverZipPath,$serverReleasePath -ScriptBlock
  {
    param($serverZipPath,$serverReleasePath)
    cd $serverReleasePath
    & 'C:Program Files7-Zip7z.exe' x -y $serverZipPath
  }
  return $true
}

For completeness, the $cred variable is called with a Credentials object to save being prompted for a password if you only specify the username. Here’s a function to help generate this object:

# Purpose : Creates PSCredential object for server authentication
# Returns : PSCredential

function CreateCredentials($user, $password)
{
     $password = convertto-securestring $password -asplaintext -force
     New-Object System.Management.Automation.PSCredential $user, $password
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.