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..
-
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.
-
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 </span> <span style="color: #000080">-CreatedByModule</span> <span style="color: #ff4500">$true</span> <span style="color: #000000">
-PSSession (
$(
& $script:NewPSSession </span> <span style="color: #000080">-ComputerName</span> <span style="color: #8b0000">'192.168.16.150'</span> <span style="color: #000000">
-ApplicationName ’/wsman’ -ConfigurationName ‘Microsoft.PowerShell’ </span> <span style="color: #000080">-SessionOption</span> <span style="color: #000000">(</span><span style="color: #0000ff">Get-PSImplicitRemotingSessionOption</span><span style="color: #000000">)</span> <span style="color: #000000">
-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’ ) ) </span> <span style="color: #000000">
-Authentication Default </span> <span style="color: #000000">
)
)
<span style="color: #0000ff">Invoke-Command</span> <span style="color: #000000">{</span><span style="color: #0000ff">Import-Module</span> <span style="color: #8a2be2">TaskScheduler</span><span style="color: #000000">}</span> <span style="color: #000080">-Session</span> <span style="color: #ff4500">$script:PSSession</span>