title: How can my local PowerShell script call a remote PowerShell script?
body: <p>Both local and remote machines have PSSession enabled.</p>
  
  <p>I think my problem is that I do not know how to convert and incoming string to  a ScriptBlock to be consumed by Invoke-Command. I can invoke all of these commands with an interactive session using Enter-PSSession.</p>
  
  <p>My local script calls the remote script in a script block. I pass the the filename and path on the command line locally with</p>
  
  <blockquote>
    <p>&amp; '.\CallRemote.ps1' -p "E:\DeployFolder\Scripts\" -f "hello.ps1"</p>
  </blockquote>
  
  <p>The local script looks like this</p>
  
  <pre><code>Param(
  [parameter(Mandatory=$true)]
  [alias("p")]
  $ScriptPath,
  [parameter(Mandatory=$true)]
  [alias("f")]
  $Scriptfile)
  if ($ScriptPath[$ScriptPath.Length - 1] -eq '\')
  {
      $ScriptBlock = $ScriptPath + $Scriptfile
  }
  else
  {
      $ScriptBlock = $ScriptPath + '\' + $Scriptfile
  }
  $appserver = "someurl.com"
  
  $pw = convertto-securestring -AsPlainText -Force -String "password"
  $cred = new-object -typename System.Management.Automation.PSCredential -$argumentlist "domain\svc.account",$pw
  
  #initiate remote session for deployment
  $session = New-PSSession -ComputerName $appserver -Credential $cred -Name test_remote
  
  #call remote script
  Invoke-Command -Session $session -ScriptBlock { $ScriptBlock}
  Remove-PSSession -Name test_remote
  </code></pre>
  
  <p>If I hard-code the Path and Filename prepending a '&amp;' it works. I have found no way to get this to work without hard-coding.</p>
  
  <p>This particular hard-coding works
  <code>Invoke-Command -Session $session -ScriptBlock { &amp; "E:\DeployFolder\Scripts\hello.ps1"}</code></p>
  
  <p>These attempts at changing the incoming strings for file and path fail quietly with  Invoke-Command -Session $session -ScriptBlock {$ScriptBlock}</p>
  
  <ol>
  <li>$ScriptBlock = "<code>&amp;</code>' " + $ScriptPath + '\' + $Scriptfile + "`'"</li>
  <li>$ScriptBlock = "&amp; <code>' " + $ScriptPath + '\' + $Scriptfile + "</code>'"</li>
  <li>$ScriptBlock = "$ScriptPath + '\' + $Scriptfile</li>
  </ol>
  
  <p>This just fails right out
  <code>Invoke-Command -Session $session -ScriptBlock { &amp; $ScriptBlock}</code>
  with the error message:</p>
  
  <blockquote>
    <p>The expression after '&amp;' in a pipeline element produced an invalid
    object. It must result in a command name, script block or CommandInfo
    object.
        + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : BadExpression</p>
  </blockquote>