Search code examples
powershelljenkinspsexec

PSExec Pass argument with spaces for powershell


With PSexec tool, I am invoking a powershell session on remote computer and executing a PS1 script. I need to pass argument to this powershell script file. It works fine if the argument does not contain space. If the argument does contain space, everything after space is trimmed.

Below is my command:

$script="<PATH>"
$args = "%ProjectSourcePath%"

cmd /c %psexecpath% \\<REMOTE SERVER>   -u <UNAME> -p <PASSWORD> -h  "c:\windows\system32\windowspowershell\v1.0\powershell.exe" $script $args

where "%ProjectSourcePath%" is the environment variable.

Background: I am using this command in Jenkins Automated Build tool. And have added this script in Windows Powershell script block.


Solution

  • First thing first, in order to run psexec straight from the command line, add the sysinternals (or wherever your psexec location) folder to the PATH with this cmd

    SET PATH=%PATH%;[FOLDER]
    

    Next up, running the command line...

    I've created a really simple script creating file with the nameof the argument im passing

    param (
        [string]$name = "defaultname"
     )
    
    $array = "string"
    
    $array | out-file "C:\Temp\Script Location\$name.txt"
    

    When running it from the remote server im doing the following:

    psexec \\build -h "C:\windows\system32\windowspowershell\v1.0\powershell.exe" "-File" "C:\temp\script location\script.ps1" "argument with space"
    

    ending up with file named "argument with space.txt"