与 PowerShell CmdLet 互操作 [英] Interoping With PowerShell CmdLets

查看:61
本文介绍了与 PowerShell CmdLet 互操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在编写一些将 PowerShell Cmdlets 用于 App-V 的实用程序.有趣的是,Microsoft 似乎只记录 cmdlet,而不记录 Powershell 模块背后使用的 .net 程序集.

I've been writing some utilities that make use of PowerShell Cmdlets for App-V. The interesting part is Microsoft seems to only document the cmdlets and not the .net assemblies used behind the Powershell modules.

现在我熟悉 P/Invoke 和 COM Interop,并且我已经学会了如何使用 System.Management.Automation 创建一个 powershell 会话并调用 cmdlet.

Now I'm familiar with P/Invoke and COM Interop and I've learned how to use System.Management.Automation to create a powershell session and invoke the cmdlets.

但有些东西我觉得不太对劲.我基本上是在编写自己的包装类来隐藏其余代码中的 powershell 调用.似乎我应该 a) 绕过 powershell 并直接进入它背后的托管库,或者 b) 应该有更好的机制来为 powershell cmdlet 生成互操作库.

But something doesn't smell right to me. I'm basically writing my own wrapper classes to hide the powershell invocations from the rest of my code. It seems like I should either a) bypass powershell and go straight for the managed library behind it or b) there should be better mechanism for generating interop libraries for powershell cmdlets.

最近微软似乎在大量使用 PS CmdLets,它实际上正在成为一种新的 API 以进行互操作.

It seems like Microsoft is making a lot of use of PS CmdLets these days that it's essentially becoming a new API to interop with.

我错过了什么吗?在这种情况下使用的好策略是什么?

Am I missing something? What's a good strategy to use in this scenario?

推荐答案

关于气味",您说得对.绕过 powershell 并不是编写实用程序的最佳方式,因为它背后的未记录的托管库比 cmdlet 更有可能默默更改.使用这种方法可能会给您带来麻烦.

You are right about the "smell". Bypassing the powershell is not the best way to write your utility, because undocumented managed library behind it are more likely to change silently than cmdlets. Using this approach can get you into trouble.

您正在尝试组合几乎无法组合的东西.解决方案是引入一个代理,允许以更自然的方式将您的代码与 ps cmdlet 结合起来.

You are trying to combine hardly combinable things. Solution is to introduce a proxy that allows to combine your code with ps cmdlets in more natural way.

在您的情况下,可以创建 ps 脚本,以自然的方式与 cmdlet 通信并提供必要的功能.在您的 c# 代码中,您可以简单地调用 powershell.exe.如果这也不适合您,那么只需使用 System.Management.Automation 来创建 powershell 会话并调用您的脚本.这种方法更安全,因为现在您可以与 powershell 代理中记录的 ps cmdlet 进行通信(自然的 powershell 方式),并通过 c# 代码与您的 ps 脚本进行通信(这使您可以更好地控制代码)

In your situation the ps script can be creates that communicates with cmdlets in natural way and provides the necessary functonality. In your c# code you can simply call the powershell.exe. If that doesn't smell right for you as well, then just use System.Management.Automation to create powershell session and invoke your script. This approach is safer, because now you communicate with documented ps cmdlets in your powershell proxy(natural powershell way), and communicate with your ps script from c# code (that gives you more control over the code)

这篇关于与 PowerShell CmdLet 互操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆