2

I want to execute my script with command line. I use function inside my script.

I used this script:

Function Get-IniFile
{
    Param(
    [parameter(mandatory=$true)][string]$FilePath
    )
    $input_file = $FilePath
    $ini_file = @{}

    Get-Content $input_file | ForEach-Object {
    $_.Trim()
    } | Where-Object {
    $_ -notmatch '^(;|$)'
    } | ForEach-Object {
    if ($_ -match '^\[.*\]$') {
        $section = $_ -replace '\[|\]'
        $ini_file[$section] = @{}
    } else {
        $key, $value = $_ -split '\s*=\s*', 2
        $ini_file[$section][$key] = $value
    }
    }

        $Get = $ini_file.Class.Amount
        $Get
}

I execute this script from command line with this command:

PowerShell.ps1 Get-IniFile -FilePath

I dont get any result when I execute this code, but If I remove "Function Get-IniFile" I got the value of Amount.

This is my INI file

[Class]
Amount = 1000
Feature = 20

[Item]
Set = 100
Return = 5

1 Answer 1

2

You have to call your function inside your script. The script code is like your main function in C# or Java.

PowerShell.ps1 content :

# Global script parameters.
Param(
    [parameter(mandatory=$true)][string]$FilePath
)

# Definition of the function
Function Get-IniFile
{
    Param(
    [parameter(mandatory=$true)][string]$Path
    )
    $input_file = $Path
    $ini_file = @{}

    Get-Content $input_file | ForEach-Object {
    $_.Trim()
    } | Where-Object {
    $_ -notmatch '^(;|$)'
    } | ForEach-Object {
    if ($_ -match '^\[.*\]$') {
        $section = $_ -replace '\[|\]'
        $ini_file[$section] = @{}
    } else {
        $key, $value = $_ -split '\s*=\s*', 2
        $ini_file[$section][$key] = $value
    }
    }

        $Get = $ini_file.Class.Amount
        $Get
}

# Calling the function with the global parameter $FilePath
Get-IniFile $FilePath
Sign up to request clarification or add additional context in comments.

1 Comment

@Job you're welcome, but I rejected your edit because I think it's best practice to differ global parameters and local ones. For example you can (in a future version) add Test-Path -Path $FilePath to test if the file exists before calling Get-IniFile

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.