当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 构建 Inception 风格的 PowerShell 模块

作者:精品下载站 日期:2024-12-14 08:05:13 浏览:15 分类:玩电脑

构建 Inception 风格的 PowerShell 模块


[玩转系统] 构建 Inception 风格的 PowerShell 模块

在过去一周左右的时间里,我一直在分享用于使用 PowerShell 函数和脚本的 PowerShell 函数和脚本。我展示了将函数导出到脚本文件的 PowerShell 函数以及将脚本转换为函数的代码。这一切都非常像 Inception。总而言之,我想分享一个我编写的 PowerShell 脚本,用于将我共享的所有代码转换为新模块。我最终会将 PSFunctionTools 发布到 PowerShell Gallery,并且我认为它没有理由不能在 Windows PowerShell 或 PowerShell 7 中工作。甚至跨平台。

该脚本甚至可能是附加功能的基础。或者我可能会将其作为参考示例包含在新模块中。让我费解的是,我正在使用代码中的函数本身来创建新的东西。我不希望您能够运行此脚本,因为它是为我的环境和文件编写的。我上周发布了所有代码,但我的文件可能与您的不同。

该脚本基于我作为将脚本转换为 PowerShell 模块的概念验证而发布的脚本。我的脚本还将在 git 中初始化新项目并使用 Platyps 模块生成初始帮助文档。

#requires -version 5.1
#requires -module Platyps

#Export functions from files and create a new module

[cmdletbinding(SupportsShouldProcess)]
Param(
    [Parameter(position = 0,HelpMessage = "What is the name of the new module?")]
    [ValidateNotNullOrEmpty()]
    [string]$NewModuleName = "PSFunctionTools",

    [Parameter(Position = 1,HelpMessage = "What is the parent path for the new module?")]
    [ValidateNotNullOrEmpty()]
    [ValidateScript({Test-Path $_})]
    [string]$ParentPath = "C:\Scripts",

    [Parameter(HelpMessage = "Enter an module description.")]
    [string]$Description = "A set of PowerShell commands for working with PowerShell scripts and functions.",

    [Parameter(HelpMessage ="PowerShell script files with functions to export.")]
    [ValidateNotNullOrEmpty()]
    [ValidateScript({Test-Path $_})]
    [string[]]$Files = $(
        'C:\scripts\Convert-FunctionToFile.ps1',
        'C:\scripts\new-folderlayout.ps1',
        'C:\scripts\dev-scripttofunction.ps1'
        )
)

Write-Verbose "Starting $($MyInvocation.MyCommand)"

<#
dot source the conversion functions

C:\scripts\Convert-FunctionToFile.ps1
  Test-FunctionName
  Get-FunctionName
  Get-FunctionAlias
  Export-FunctionFromFile
C:\scripts\New-FolderLayout.ps1
  Import-ModuleLayout
  Export-ModuleLayout
#>
. C:\scripts\Convert-FunctionToFile.ps1
. C:\scripts\New-FolderLayout.ps1

#the new module location
$path = Join-path -Path $ParentPath -ChildPath $NewModuleName
$export = [System.Collections.Generic.list[object]]::New()
$aliases = @()
#the layout was created using Export-ModuleLayout
$layout = "C:\scripts\ModuleLayout.json"
Write-Verbose "Creating the module structure"
Import-ModuleLayout -Name $NewModuleName -ParentPath $ParentPath -Layout $layout

#I removed the parameter validation on the target path
$functionFiles = $files | ForEach-Object {
    Write-Verbose "Processing $_"
    Export-FunctionFromFile -Path $_ -OutputPath $Path\functions\public -All -Passthru
    #get aliases
    if ($pscmdlet.ShouldProcess($_,"Getting function aliases")) {
        $aliases += Get-FunctionAlias -path $_ | Select-Object -ExpandProperty alias
    }
}

if ($functionFiles) {
    $export.AddRange($functionFiles.baseName)
}

#create the root module
$psm1 = @"

Get-Childitem `$psscriptroot\functions\*.ps1 -recurse |
Foreach-Object {
. `$_.FullName
}

"@
Write-Verbose "Creating root module $path$newmodulename.psm1"
$psm1 | Out-File "$path$newmodulename.psm1"

#create the module manifest
$splat = @{
    Path                 = "$path$newmodulename.psd1"
    RootModule           = "$newmodulename.psm1"
    ModuleVersion        = "0.1.0"
    Author               = "Jeff Hicks"
    CompanyName          = "JDH Information Technology Solutions, Inc."
    Copyright            = "(c) 2021 JDH Information Technology Solutions, Inc."
    Description          = $Description
    CmdletsToExport      = @()
    VariablesToExport    = @()
    FunctionsToExport    = $Export
    AliasesToExport      = $aliases
    PowerShellVersion    = "5.1"
    CompatiblePSEditions = "Desktop","Core"
}
Write-Verbose "Creating module manifest $($splat.path)"
New-ModuleManifest @splat

#this requires the Platyps module
Write-Verbose "Creating module help files"
if ($PSCmdlet.ShouldProcess("docs","create markdown help files")) {
    Import-Module $splat.path
    New-MarkdownHelp -Module $NewModuleName -OutputFolder $path\docs
    New-ExternalHelp -Path $path\docs -OutputPath $path\en-us
}

Write-Verbose "Initializing git"
if ($PSCmdlet.ShouldProcess($path, "git initialize")) {
    Set-Location $path
    git init
    git add .
    git commit -m "initial files"
    git checkout -b $splat.ModuleVersion
}

if (-not $WhatIfPreference) {
    Get-ChildItem $path -Recurse
    Try {
        [void](Get-Command -name code.cmd -ErrorAction stop)
        Write-Verbose "Opening module in VSCode"
        code $path
    }
    Catch {
        Write-Warning "VS Code not found."
    }
}

Write-Verbose "Ending $($MyInvocation.MyCommand)"

我对脚本进行了参数化,以便将其变成可重用的工具。但目前,参数值是硬编码的,以节省我的打字时间。

该脚本有几个阶段。首先,它使用我共享的命令创建模块结构,以导出和导入模型模块目录结构。其次,该脚本获取文件数组并将所有函数导出到单独的文件中。第三,它创建一个根模块,并且该模块清单使用导出函数中的信息。接下来,该脚本创建帮助文档并最终初始化 git。如果我没有使用 -WhatIf 运行脚本,新模块将在 VSCode 中打开。

[玩转系统] 构建 Inception 风格的 PowerShell 模块

我已经运行了这个脚本并开始处理该模块,但我希望您看到输出,所以这是使用临时文件夹和 -Whatif。

[玩转系统] 构建 Inception 风格的 PowerShell 模块

在这里你可以看到 VSCode 中的结果。整个过程持续了大约3秒。我肯定会开发这个想法并亲自使用它。我经常从独立的脚本文件开始,最终我决定将其转换为模块。如果有一套工具来加速这一过程,那就太好了。

同时,请随意使用我分享的任何代码来构建您自己的 PowerShell 工具来构建 PowerShell 工具。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯