Как использовать функцию в PowerShell для выполнения из командной строки? - PullRequest
2 голосов
/ 22 марта 2019

Я хочу выполнить свой скрипт с командной строкой. Я использую функцию внутри моего скрипта.

Я использовал этот скрипт:

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
}

Я выполняю этот скрипт из командной строки с помощью этой команды:

PowerShell.ps1 Get-IniFile -FilePath

Я не получаю никакого результата при выполнении этого кода, но если я удалю «Function Get-IniFile», я получу значение Amount.

Это мой INI-файл

[Class]
Amount = 1000
Feature = 20

[Item]
Set = 100
Return = 5

1 Ответ

2 голосов
/ 22 марта 2019

Вы должны вызывать свою функцию внутри скрипта.Код сценария похож на вашу main функцию в C # или 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...