Search code examples
powershellsessionpowershell-remoting

How to Properly Put together a Function in Powershell


I have done a ton of research on how to push this EXE to a remote PC using PSSession and all lines of code work when executed line by line. But i have had a hard time putting this into a function that makes sense and will execute all lines of code and successfully install the software with one push of a button. Not sure whats happening. It will install the exe locally when i tried to do put all lines of code in a function and run it. Can you please help instruct what i am doing wrong? Sorry i am a newbie at Powershell.

  $dc1 = New-PSSession -ComputerName DC1
  Copy-Item C:\TPAdmin\Greenshot-INSTALLER-1.2.10.6-RELEASE.exe -Destination C:\TPAdmin -ToSession $dc1
  Enter-PSSession -Session $dc1
  Invoke-Command -ScriptBlock {C:\TPAdmin\Greenshot-INSTALLER-1.2.10.6-RELEASE.exe /VERYSILENT /LOG="C:\SOFTWAREINSTALL.LOG" 
 Remove-Pssession $dc1

Solution

  • Enter-PSSession is for interactive use only, so not suitable for use in a function.[1]

    Instead of using Enter-PSSession, pass the session you've created with New-Session to the Invoke-Command command's -Session parameter, which will run the command in the context of that (remote) session.

    # Define your function...
    function Invoke-InstallerRemotely {
      param([string] $ComputerName)
      $session = New-PSSession -ComputerName $ComputerName
      Copy-Item C:\TPAdmin\Greenshot-INSTALLER-1.2.10.6-RELEASE.exe -Destination C:\TPAdmin -ToSession $session
      # Do NOT use Enter-PSSession.
      # Pass your session to Invoke-Command with -Session
      Invoke-Command -Session $session -ScriptBlock {C:\TPAdmin\Greenshot-INSTALLER-1.2.10.6-RELEASE.exe /VERYSILENT /LOG="C:\SOFTWAREINSTALL.LOG" 
      Remove-PSSession $session
    }
    
    # ... then invoke it.
    # Note that functions must be defined *before* they're called.
    Invoke-InstallerRemotely -ComputerName DC1
    

    [1] Using it in a function means that an interactive session on the target computer is entered, which you must exit interactively (by typing and submitting exit or Exit-PSSession) before the remaining statements in the function are executed, again locally.