Skip to content

Instantly share code, notes, and snippets.

@stuartpreston
Created March 23, 2015 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stuartpreston/c63b548c294a33ccb2a2 to your computer and use it in GitHub Desktop.
Save stuartpreston/c63b548c294a33ccb2a2 to your computer and use it in GitHub Desktop.
Dot-sourcing script on a machine via remote (e.g. WinRM) session

Example function to be saved to c:\winrm-profile.ps1

function Get-Hostname
{
  return $env:COMPUTERNAME
}

To invoke normally:

$s = New-PSSession -computername remotemachine
Invoke-Command -ScriptBlock {. c:\winrm-profile.ps1; Get-Hostname} -Session $s

For a background job you need to do something like:

Invoke-Command -ScriptBlock {Start-Job {Get-Hostname} -InitializationScript {. c:\winrm-profile.ps1}} -Session $s

To check the output of the job to make sure it ran the function from the "profile":

Invoke-Command -ScriptBlock {(Get-Job).childjobs | Select Output} -Session $s

Should return something like:

Output                                  PSComputerName                          RunspaceId
------                                  --------------                          ----------
{SPVM2015}                              Localhost                               b9e22007-ce49-4e8b-8e57-986973b32be8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment