2

I have a C# PSCmdlet class for implementing a PowerShell command and I want to get my module version while running the command.

I don't want to get the version from the assembly location because I need the actual version loaded (it can be different, for example, if I keep PowerShell open while upgrading my module, the assembly will point to the upgraded version and I won't get the one that already loaded).

I need something like Get-Module for the current session but from my C# command code.

How can I do it?

4

2 回答 2

1

差不多一年后我一直在进行同样的十字军东征,这就是我想出的:

$version = Split-Path -Leaf $MyInvocation.MyCommand.ScriptBlock.Module.ModuleBase
于 2021-11-22T09:34:03.287 回答
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... 
#>
于 2020-12-16T23:15:51.840 回答