Search code examples
powershellpowershell-2.0powershell-3.0powershell-4.0powershell-remoting

PowerShell: remote execution of console application fails


While running the following snippet in powershell, I see an error(an error occurred while creating the pipeline). can anyone help me here?

# This file contains the list of servers you want to copy files/folders to
$computers = gc "C:\folder1\sub1\server.txt"
 
# This is the file/folder(s) you want to copy to the servers in the $computer variable
$source = "\\usa-chicago1\c$\Program Files\"
 
# The destination location you want the file/folder(s) to be copied to
$destination = "c$\July\"
$username = 'harry'
$password = 'hqwtrey$1'
$secpw = ConvertTo-SecureString $password -AsPlainText -Force
$cred  = New-Object Management.Automation.PSCredential ($username, $secpw)


foreach ($computer in $computers) {
if ((Test-Path -Path \\$computer\$destination)) {

     Write-Output "INSIDE IF BLOCK"
    #Copy-Item $source -Destination \\$computer\$destination -Recurse
    Invoke-Command -Computername $computer -ScriptBlock { & '\\$computer\July\' --service install --config-directory '\\$computer\July\conf' } 
    Invoke-Command -Computername $computer -ScriptBlock { & net start telegraf } 
} 
else {
    
    Write-Output $computer
    New-Item -Path "\\$computer\july\" -ItemType Directory
    Write-Output \\$computer\$destination
    Copy-Item $source -Destination \\$computer\$destination -Recurse
}
}
 

Solution

    • Script blocks passed to Invoke-Command -ComputerName ... execute remotely, and the remote session knows nothing about the caller's variables; refer to the caller's variables via the $using: scope - see this answer.

    • Variable references can only be embedded in double-quoted strings ("..."), whereas single-quoted strings ('...') treat their content verbatim - see the bottom section of this answer for an overview of PowerShell string literals.

    Therefore:

    Invoke-Command -Computername $computer -ScriptBlock { 
      & "\\$using:computer\July\Telegraf\telegraf" --service install --config-directory "\\$using:computer\July\Telegraf\conf"
    } 
    

    As for the nondescript error message you saw, RuntimeException: An error occurred while creating the pipeline.:

    This should be considered a bug; you should see &: The term '\\$computer\July\Telegraf\telegraf' is not recognized as the name of a cmdlet, function, script file, or operable program., as you would get with local invocation.

    The bug, which only surfaces with UNC paths, is being tracked in this GitHub issue.