编写本地和远程使用的 PowerShell 脚本的最佳实践

发布于 2024-08-29 09:37:45 字数 88 浏览 2 评论 0原文

编写将在远程上下文中执行的脚本的最佳实践有哪些?

例如,我刚刚发现内置 var $Profile 在远程执行期间不存在。

What are some of the best practices for 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

_失温 2024-09-05 09:37:45

配置文件

您已经发现了一个主要区别,$profile 未配置。

MSDN 中隐藏了一些有关远程 powershell 的常见问题,或者执行 获取有关_Remote_FAQ的帮助

在“我的个人资料在哪里?”下(呵呵)它解释说:

例如,以下命令运行 C​​urrentUserCurrentHost 配置文件
来自 $s 会话中的本地计算机。

    invoke-command -session $s -filepath $profile

以下命令运行 C​​urrentUserCurrentHost 配置文件
$s 中会话中的远程计算机。因为 $profile 变量
未填充,该命令使用配置文件的显式路径。

    invoke-command -session $s {. "$home\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1"}

序列化

可能影响您的另一个区别是,命令返回的 .NET 对象不是直接返回,而是当您远程运行它们并返回它们时,它们会通过网络进行序列化和反序列化。许多对象支持这一点,但有些对象不支持。 Powershell 会自动删除不再“挂钩”的对象上的方法,然后它们基本上是数据结构......但它确实会重新挂钩某些类型(例如 DirectoryInfo)上的方法。

通常你不必担心这一点,但如果你通过管道返回复杂的对象,你可能......

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...

腻橙味 2024-09-05 09:37:45

脚本块不像通常那样充当闭包:

$var = 5
$sb={ $var }
&$sb # 5
Start-Job $sb | Wait-Job | Receive-Job # nothing

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文