C# - 如何在运行时从模块代码内获取PowerShell模块版本

4
我有一个C# PSCmdlet类用于实现PowerShell命令,我希望在运行命令时获取我的模块版本。
我不想从程序集位置获取版本,因为我需要已加载的实际版本(例如,如果我在升级模块时保持PowerShell打开,程序集将指向升级的版本,而我将无法获得已经加载的版本)。
我需要像Get-Module一样获取当前会话的内容,但是要从我的C#命令代码中获取。
我该如何做?

在每个会话中,加载所有默认/所需的模块和其他内容,然后在您的会话中将其与您加载的内容进行比较以进行检查。 - postanote
3个回答

1

作为我进行了近一年的同一项任务,这是我的成果:

$version = Split-Path -Leaf $MyInvocation.MyCommand.ScriptBlock.Module.ModuleBase

1
这对我有用:
$MyInvocation.MyCommand.ScriptBlock.Module.Version

它基于ModuleBase答案,但仅在版本号是路径的最后一部分时才有效,这并不总是保证的。


0

根据我的评论提供详细信息。因此,在PowerShell中,可能是这样的...

# Put this in your profile (ISE/PowerShell/VSCode)
$AutomaticModules     = Get-Module

$AutomaticModules
# Results
<#
ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Binary     1.0.0.0    CimCmdlets                          {Export-BinaryMiLog, ...
Script     1.1.0      ClassExplorer                       {Find-Member, Find-Na...
...
#>

# Get only modules loaded during the session
Compare-Object -ReferenceObject (Get-Module) -DifferenceObject $AutomaticModules -Property Name -PassThru |
Where -Property Name -ne 'AutomaticModules'

# Results
<#
ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   3.0.0.0    Microsoft.PowerShell.Security       {ConvertFrom-SecureString, ...
Manifest   3.0.0.0    Microsoft.WSMan.Management          {Connect-WSMan, Disable-WSMa...
#>

Import-Module -Name IsePester

Compare-Object -ReferenceObject (Get-Module) -DifferenceObject $AutomaticModules -Property Name -PassThru |
Where -Property Name -ne 'AutomaticModules'

# Results
<#
ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     0.0        IsePester                           {Add-PesterMenu, Get-PesterM...
Manifest   3.0.0.0    Microsoft.PowerShell.Security       {ConvertFrom-SecureString, C...
Manifest   3.0.0.0    Microsoft.WSMan.Management          {Connect-WSMan, Disable-WSMa...
#>

所以,作为一个函数:

function Get-SessionModule
{
    Param
    (
        [String]$ModuleName
    )

    (Compare-Object -ReferenceObject (Get-Module) -DifferenceObject $AutomaticVModules -Property Name -PassThru |
    Where -Property Name -ne 'AutomaticVModules') -Match $ModuleName
}

Get-SessionModule -ModuleName IsePester
# Results
<#
ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Script     0.0        IsePester                           {Add-PesterMenu, Ge... 
#>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接