简体   繁体   English

Powershell 核心和 Powershell 模块

[英]Powershell Core and Powershell Modules

I have a need to create a Module that can Run in Powershell 7 and use commandlets from Powershell 5.我需要创建一个可以在 Powershell 7 中运行并使用来自 Powershell 5 的命令行开关的模块。

I want to save this module as an artifact and publish in AzureDevOps Artifacts.我想将此模块保存为工件并在 AzureDevOps Artifacts 中发布。

The Module is for auditing cross platform system information.该模块用于审计跨平台系统信息。 The problem is that some of the cmdlets are Windows platform specific such as Get-WindowsFeature .问题在于某些 cmdlet 是特定于 Windows 平台的,例如Get-WindowsFeature I also want to use PowerShell Core functions such as Azure Cosmos communication cmdlets.我还想使用 PowerShell 核心功能,例如 Azure Cosmos 通信 cmdlet。

How do I load functions only on certain platforms?如何仅在某些平台上加载功能?

Do you need to write something in C# to achieve this, or nest a module for a specific platform in my main module?您是否需要用 C# 编写一些东西来实现这一点,或者在我的主模块中为特定平台嵌套一个模块?

The comments mention correctly you can wrap up a command with a version check.注释正确提到您可以使用版本检查来结束命令。 That's a great option for a small use command.对于小型使用命令来说,这是一个很好的选择。 I'd recommend as a better module design to just have two modules, one for each platform.作为更好的模块设计,我建议只有两个模块,每个平台一个。 This would allow you to better seperate your work, and not rely on many embedded logic steps that conditionally run actions on different platforms.这将使您能够更好地分离您的工作,而不是依赖于有条件地在不同平台上运行操作的许多嵌入式逻辑步骤。 To me this is just cleaner.对我来说,这只是更清洁。

As you get started on modules, I'd highly recommend you use a template to bootstrap your project.当您开始使用模块时,我强烈建议您使用模板来引导您的项目。 I've found that it saves a lot of time, and sets me up for best practices.我发现它节省了大量时间,并为我提供了最佳实践。

My personal favorite is PSModuleDevelopment which you can use like this:我个人最喜欢的是PSModuleDevelopment ,你可以像这样使用它:

Install-Module PSModuleDevelopment -Scope CurrentUser
Get-Help 'Invoke-PSMDTemplate'

This is very similar to the loading structure some very mature projects like dbatools and PSFramework use.这与一些非常成熟的项目如 dbatools 和 PSFramework 使用的加载结构非常相似。 If you use this, you benefit primarily from:如果您使用它,您将主要受益于:

  • Being able to seperate all your functions into their own files and load them easily能够将所有功能分离到自己的文件中并轻松加载它们
  • Some nice enhancements to preload configurations in your module对模块中预加载配置的一些不错的增强
  • Pester test template included包括 Pester 测试模板

I stopped trying to write my own module structure and just leveraged a development module like this, and it's been very helpful for me.我不再尝试编写自己的模块结构,而是利用了这样的开发模块,这对我非常有帮助。

Good luck!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM