简体   繁体   中英

How do I use Function in PowerShell to execute from Command Line?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM