powershell - 如何在远程 session 中执行字符串形式的PowerShell block ,而不是ScriptBlock?

标签 powershell powershell-remoting powershell-3.0

我正在尝试在远程PowerShell session 中自定义提示。一切正常:

$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

它创建一个 session ,为方便起见设置PSDrive,然后将提示自定义为“测试”。

但是,我不想我的提示说“测试”,我想执行一些code that colours the server name。但是,我不想在脚本块(上面的a)中对其进行硬编码,因为我想在许多类似的函数中重用它以连接到不同类型的服务器。

因此,我已经在本地定义了该函数,并且可以使用“Get-Content function:\ RemotePrompt”获取内容。但是,我正在努力弄清楚如何将其发送到另一个 session 。 Invoke-Expression似乎不需要 session ,并且Invoke-Command似乎总是希望使用脚本块。

我真正想做的是像Invoke-Command -ScriptBlock { function prompt $MyRemoteCode }这样的东西,但是变量是“resolved”的。

这可能/容易吗?

最佳答案

在Powershell V3中,以$ using:为前缀的变量会自动识别为本地变量,并发送到远程计算机
所以你可以使用PS>$test="local var"
PS>icm -cn server1 -ScriptBlock{write-host $using:test}
local var

您可以在此处查看V3的所有新功能:http://blogs.msdn.com/b/powershell/archive/2012/06/14/new-v3-language-features.aspx

关于powershell - 如何在远程 session 中执行字符串形式的PowerShell block ,而不是ScriptBlock?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13699315/

相关文章:

powershell - 列出物理驱动器空间

powershell - Powershell : How to check the good execution of a batch file on a remote computer using invoke-command

powershell - 如何使用 PowerShell 进行远程注册表更改?

powershell - 为什么此代码将开关参数传递给 PowerShell 函数会失败

sharepoint - 使用 PowerShell 从 SharePoint Online 下载文件

powershell - 如何从 Powershell v3 调用无参数泛型方法?

powershell - 我可以从 Export-ModuleMember 中排除单个函数吗?

powershell - 我需要在网络共享上找到一个文件夹

powershell - 使用 powershell 单击超链接

Powershell v2 远程处理和委派