powershell - 在 PowerShell 中通过管道传输到对象/属性/方法

标签 powershell piping

在 PowerShell 中,您可以通过管道传输到 Cmdlet 和脚本函数中。但是是否可以通过管道传递到对象、属性或成员函数中?

例如,如果我有一个数据库连接对象$dbCon ,我希望能够做这样的事情:

$dbCon.GetSomeRecords() | <code-to-manipulate-those-records | $dbCon.WriteBackRecords()

我知道使用 Foreach-Object 可以实现相同的功能或者使用获取对象作为参数的 Cmdlet - 我想直接通过管道传递给对象或其成员的原因是为了实现优雅并保持 OOP 风格(使用对象的方法而不是将对象作为参数发送)

这可能吗?


编辑:

看来大家不明白我的问题,所以我需要澄清一下:

PowerShell 可以通过管道传递给普通函数。我会写:

function ScriptedFunction
{
    $input|foreach{"Got "+$_}
}
1,2,3|ScriptedFunction

然后得到
Got 1<br/> Got 2<br/> Got 3
作为结果。但是当我尝试通过脚本方法使用该技术时:

$object=New-Object System.Object
$object|Add-Member -MemberType ScriptMethod -Name ScriptedMethod -Value {$input|foreach{"Got "+$_}}
1,2,3|$object.ScriptedMethod

我收到一条错误消息:Expressions are only allowed as the first element of a pipeline. (添加 () 对 BTW 没有帮助)。我正在寻找一种方法,使该命令的工作方式与它在全局函数中的工作方式相同。

最佳答案

这不完全是您要求的,但它具有几乎相同的语法:使用 NoteProperty 而不是 ScriptedMethod 并使用运算符 .& 调用它:

$object = New-Object System.Object
$object | Add-Member -MemberType NoteProperty -Name Script -Value {$input|foreach{"Got "+$_}}
1,2,3 | & $object.Script

输出

Got 1
Got 2
Got 3

但是: 有一个警告,也许是一个表演障碍:这根本不是脚本方法,核心不会为它定义 $this(你可以定义 $this = $object 在自己调用之前,但这相当难看,将 $object 作为参数发送会更好。

关于powershell - 在 PowerShell 中通过管道传输到对象/属性/方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7635262/

相关文章:

c# - EntityFramework 6.0 CreateDatabaseIfNotExists 代码先创建数据库

powershell - 使用 Session 和 CredSSP 的 PSRemoting 错误

powershell - 是否可以在 PowerShell 中使用带有嵌套哈希表的 splatting?

windows - 在 Apache Spark 中通过管道运行 Windows 批处理文件

unix - 将远程文件放入 hadoop 而不将其复制到本地磁盘

regex - 在 Powershell 中使用正则表达式抓取电子邮件

powershell - 如何在 Powershell 中处理包含括号的变量

c - 管道实现

c++ - 从 C/C++ 调用时,Objective C stdin/stdout 管道如何工作?

javascript - 如何在 Javascript 中将一种方法的输出传输到另一种方法的输入?