【发布时间】: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