Monday, May 1, 2023

How to load hash table from file in PowerShell script

### We can defne hashtabe in file and load that hashtable from file in PS , we can use this hashtable as configuration information.



Following PS_Utility.psd1 manifestfile is having hashtable. ```sh @{ # Script module or binary module file associated with this manifest. RootModule = 'PS-Utility.psm1' # Version number of this module. ModuleVersion = '1.0.0' # Supported PSEditions # CompatiblePSEditions = @() # Description of the functionality provided by this module Description = '' # Minimum version of the Windows PowerShell engine required by this module PowerShellVersion = '' # Name of the Windows PowerShell host required by this module PowerShellHostName = '' # Minimum version of the Windows PowerShell host required by this module PowerShellHostVersion = '' # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. DotNetFrameworkVersion = '' # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. CLRVersion = '' # Processor architecture (None, X86, Amd64) required by this module ProcessorArchitecture = '' # Modules that must be imported into the global environment prior to importing this module RequiredModules = @() # Assemblies that must be loaded prior to importing this module RequiredAssemblies = @() # Script files (.ps1) that are run in the caller's environment prior to importing this module. ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess NestedModules = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = @("Convert-ToHashTable" , "Get-ConfigValues" , "Get-Parent" , "Get-Servers" , "Get-UtilityScriptPath" , "Convert-ToList" , "Convert-ToString" , "New-ItemIfNotExits" , "Test-ChangeTransactionID" , "Initialize-Logging" , "Get-ErrorLog" , "Get-MessageLog" , "Write-Error" , "Write-Message" , "Write-Failure" , "Write-Success" , "Get-TranscriptRunningState" , "Set-TranscriptRunningState" , "Initialize-SendEmail" , "Send-Email" ) } ``` Following code can read manifest PS-Utility.psd1 file and load into Powershell session ```sh $ManifestFile =".\PS-Utility.ps1" if (Test-Path $ModuleName){ $ModuleConfig=(Invoke-Expression $(Get-Content $ManifestFile | out-string )) $RootModule=$ModuleConfig["RootModule"] $ModuleConfig["FunctionsToExport"] |&{Process{ $_}} } ```

No comments:

Post a Comment