簡體   English   中英

如何使用 PowerShell 中的函數從命令行執行?

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

我想用命令行執行我的腳本。 我在腳本中使用函數。

我使用了這個腳本:

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

您必須在腳本中調用您的函數。 腳本代碼就像 C# 或 Java 中的main函數。

PowerShell.ps1 內容:

# 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM