I'm trying to customise my prompt in a remote PowerShell session. This all works fine:
$session = New-PSSession MyRemoteServer
Invoke-Command -Session $session -ScriptBlock {
New-PSDrive -Name MyApp -PSProvider FileSystem -Root D:\Applications\MyApp | Out-Null
CD MyApp:\
function prompt { "test" }
}
Enter-PSSession -Session $session
It creates a session, sets up a PSDrive for convenience, then customises the prompt to "Test".
However, I don't want my prompt to say "test", I want to execute some code that colours the server name. However, I don't want to hard-code it in the script block (a above), because I want to reuse it in a number of similar functions for connecting to different types of servers.
So I've defined the function locally, and can get at the contents using "Get-Content function:\RemotePrompt". However, I'm struggling to figure out how to send this over to the other session. Invoke-Expression doesn't seem to take a Session, and Invoke-Command seems to always expect a script block.
What I really want to do is something like Invoke-Command -ScriptBlock { function prompt $MyRemoteCode }
but with the variable being "resolved".
Is this possible/easy?
With Powershell V3 variables prefixed with $using: are automatically recognized as local variables and are sent to the remote machine
so you can use
PS>$test="local var"
PS>icm -cn server1 -ScriptBlock{write-host $using:test}
local var
you can see all new features of V3 here : http://blogs.msdn.com/b/powershell/archive/2012/06/14/new-v3-language-features.aspx