【问题标题】:Set multiple variables in Powershell module and return it to main program在Powershell模块中设置多个变量并返回给主程序
【发布时间】:2023-03-13 17:17:01
【问题描述】:

我编写了一个 Powershell 模块,它具有一些功能,并且我在定义如下的函数内设置了多个变量:

#
# ConfigurationHelper.psm1
#
# Global Variables
$PackageLocation = ""
$LogFilePath = ""
$LogFileName = ""
$DestinationLocation = ""
$ExcludedBinariesFiles = ""
$ExcludedBinariesFolders = ""
$IncludeTransformsFiles = ""
# end global variables
# Function to read all the config settings 
function Get-ConfigSettings {
    Write-Host "Get-ConfigSetting function is called"
    #logging configuration
    [xml] $logConfigFile = Get-Content -Path (Join-Path ((Get-Item $PSScriptRoot).Parent.FullName) "\config\GlobalConfiguration.xml")
    $LogFilePath = $logConfigFile.SelectSingleNode("/configuration/LogsPath").InnerText;
    $LogFileName = $logConfigFile.SelectSingleNode("/configuration/LogsFileName").InnerText;
    $PackageLocation = (Get-Item $PSScriptRoot).Parent.FullName

    # BinariesConfiguration
    [xml] $BinariesConfig = Get-Content -Path (Join-Path ((Get-Item $PSScriptRoot).Parent.FullName) "\config\Oakton_Environments.xml")
    $environemntNodes = $BinariesConfig.SelectNodes("//environment[@Server=$env:computername]")
    if ($environemntNodes -ne 1) {
        throw "Server configuration missing or more than one environment configuration was found for server"
    }
}
Export-ModuleMember -Function * -Variable $LogFilePath

在我的 main.ps1 中

Get-ConfigSettings

$LogFilePath #this variable is empty string

即使在执行设置变量的函数之后,该变量也是空字符串。我在模块脚本的末尾完成了导出成员。如何返回模块中定义的变量?

我想返回在configurationHelper.psm1 顶部设置的多个变量。

【问题讨论】:

  • 定义一个返回值,然后像这样调用你的函数:$LogFilePath = Get-ConfigSettings
  • $LogFilePath = ... -> $global:LogFilePath = ...
  • 全局变量有效.. 只是想问从模块返回变量的最佳策略是什么.. 我应该使用全局变量还是 Export-ModuleMember,这在我的情况下似乎不起作用。

标签: powershell


【解决方案1】:

阅读并关注Export-ModuleMember docs

-Variable <String[]>
    Specifies the variables that are exported from the script module file. 
    Enter the **variable names**, **without a dollar sign**.
    Wildcard characters are permitted.

使用

Export-ModuleMember -Function * -Variable LogFilePath 

【讨论】:

    猜你喜欢
    • 2019-01-12
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 2017-03-21
    相关资源
    最近更新 更多