Best practices for writing PowerShell scripts for local and remote usage
What are some of the best practices fo开发者_JS百科r writing scripts that will execute in a remote context?
For instance, I just discovered that built-in var $Profile
doesn't exist during remote execution.
Profile
You've discovered one main difference, $profile
not being configured.
Buried in MSDN here are some FAQs about remote powershell, or do get-help about_Remote_FAQ
.
Under the "WHERE ARE MY PROFILES?" (heh) it explains:
For example, the following command runs the CurrentUserCurrentHost profile from the local computer in the session in $s.
invoke-command -session $s -filepath $profile
The following command runs the CurrentUserCurrentHost profile from the remote computer in the session in $s. Because the $profile variable is not populated, the command uses the explicit path to the profile.
invoke-command -session $s {. "$home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"}
Serialization
Another difference that may affect you is that instead of the .NET objects returned by commands being just directly returned, when you run them remotely and return them, they get serialized and deserialized over the wire. Many objects support this fine, but some do not. Powershell automatically removes methods on objects that are no longer "hooked up", and they're basically data structures then... but it does re-hook methods on some types like DirectoryInfo
.
Usually you do not have to worry about this, but if you're returning complex objects over a pipe, you might...
Script blocks don't act as closures, like they do normally:
$var = 5
$sb={ $var }
&$sb # 5
Start-Job $sb | Wait-Job | Receive-Job # nothing
精彩评论