Steven Murawski

SysAdmin, DevOps, PowerShell, and Other Stuff

Adding Configuration To Remoting

This is a pretty brief post that will need some further elaboration, but Twitter doesn’t provide the best mechanism for longer examples.

There are two places where you can configure your remote sessions..

1) On the remote server – which is covered in a number of places and probably the most discoverable place to put configuration information..  See the help for about_Session_Configurations.

2) Locally, when you start the PSSession.  This is where we will dig deeper.

 

One of the cool, lesser covered features in remoting is the ability to persist a remote connection to a module.  After you establish a PSSession, you can use Export-PSSession to create a module that will hold the commands to create the proxies for the commands in that session, as well as the plumbing to recreate that session.

Export-PSSession will create a script module, which you can modify to work how you would like.. 

In the module, one of the functions generated is the Get-PSImplicitRemotingSession function.  When you call one of the commands from the imported session, it will get the saved PSSession.  If the session has not been established yet, the Set-PsImplicitRemotingSession function will be called, creating the session.  You can add your any commands you would like after that..

For example I’m using Invoke-Command below to import a module once the session is connected.  That script block can be anything you need to do to configure your remote session. (NOTE: The Set-PSImplicitRemotingSession is generated by the command, I’m only adding code after that and using the $script:PSSession object that is created.

Set-PSImplicitRemotingSession `            -CreatedByModule $true `
            -PSSession (             
            $(             
                & $script:NewPSSession `
                    -ComputerName '192.168.16.150' `
                    -ApplicationName '/wsman'    -ConfigurationName 'Microsoft.PowerShell' `
                    -SessionOption (Get-PSImplicitRemotingSessionOption) `
                    -Credential ( $host.UI.PromptForCredential( 'Windows PowerShell Credential Request', 'Enter your credentials for http://192.168.16.150/wsman.', 'phoenix\steve.murawski', '192.168.16.150' ) ) `
                     `
                    -Authentication Default `
                   `
            )             
            )            

          Invoke-Command {Import-Module TaskScheduler} -Session $script:PSSession