[英]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.