title: Powershell Invoke-Command
body: <p>I wrote this script to execute commands on a remote machine.
  If I inkove it with no parameters it runs fine</p>
  <pre><code>PS D:\batch&gt;  .\remoteExecute.ps1 -computer myServer -command 'dir'
  
  Directory: C:\Users\AC0476BF\Documents
  
  Mode                LastWriteTime         Length Name                                  PSComputerName                       
  ----                -------------         ------ ----                                  --------------
  -----        5/31/2021   4:27 PM                WindowsPowerShell                     myServer                  
  
  Executing: 'dir' on remote computer myServer
  </code></pre>
  <p>However if I specify a parameter it returns an error.</p>
  <pre><code>PS D:\batch&gt;  .\remoteExecute.ps1 -computer myserver -command 'dir c:\windows'
  The term 'dir c:\windows' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
      + CategoryInfo          : ObjectNotFound: (dir c:\windows:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException
      + PSComputerName        : myServer
   
  Executing: 'dir c:\windows' on remote computer myServer
  </code></pre>
  <p><strong>What am I missing?</strong></p>
  <pre><code>param (
      [Parameter(Mandatory = $true, HelpMessage = &quot;Remote computer&quot;)]
      [String]$computer, 
          
      [Parameter(Mandatory = $true, HelpMessage = &quot;Command to be executed on the remote computer&quot;)]
      [String]$command, 
          
      [Parameter(Mandatory = $false, HelpMessage = &quot;Logging of command enabled to filename specified&quot;)]
      [String]$logFile,
          
      [Parameter(Mandatory = $false, HelpMessage = &quot;Execute in Command Shell. Default is PowerShell&quot;)]
      [Switch]$cmdShell
  )
   
  try {
      if ($cmdShell) {
          $command = &quot;cmd --% /c '&quot; + $command + &quot;'&quot;
      }
  
      if ($logFile) {
          $executeCommand = $command + &quot; *&gt;&gt; &quot; + $logfile
      }
      else {
          $executeCommand = $command
      }
  
      Invoke-Command -computerName $computer -ScriptBlock { &amp; $using:executeCommand } 
                  
      $message = &quot;Executing: '&quot; + $executeCommand + &quot;' on remote computer &quot; + $computer
      Write-Host $message
  
     
      exit 0
  }
  catch {
      $message = $PSItem.ToString()
      Write-Host $message
      # logging goes here...
      throw     
  }
  </code></pre>