I want to call the specific function in my powershell script from command line. But It return me error like this : Key cannot be null.
Parameter name: key $Get = $ini_file.($a_section).($b_node) Key cannot be null. Parameter name: key $Output = $ini_file.($a_section).($b_node) | Out-File $Store\Val ...
Here is my code:
Param(
[Parameter(Mandatory=$true)]
[string]$FilePath,
$ini, $a_section, $b_node, $c_store,
$a, $b, $c
)
function Get-File {
$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.($a_section).($b_node)
$Store = $c_store
$Output = $ini_file.($a_section).($b_node) | Out-File $Store\Value.cmd
}
function Write-File {
Import-Module PsIni
$ff = Get-IniContent $FilePath
$ff["$a"]["$b"] = "$c"
$ff | Out-IniFile -FilePath $FilePath -Force
}
# Calling the function with the global parameter $FilePath
Write-File $FilePath $a $b $c
Get-File $FilePath $ini $a_section $b_node $c_store
The way I call each function from command line is:
Call function Get-File:
powershell.ps1 Get-File -FilePath C:\User\file.ini -a_section Information -b_node Name -c_store C:\User\
If I run that command, I still can get the value of INI file, but it returns the above error. If I REMOVE this part Write-File $FilePath $a $b $c It will not return any error.
It looks like I can't use "calling the function" at the same time. But I am not sure about it.
My INI file
[Information]
Name=Joyce
Age=12
UPDATED CODE:
Function Read-File
{
Param(
[parameter(mandatory=$true)]$FilePath,
[parameter(mandatory=$true)] $ini,
[parameter(mandatory=$true)] $a_section,
[parameter(mandatory=$true)] $b_node,
[parameter(mandatory=$true)] $c_store
)
$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.($a_section).($b_node)
$Store = $c_store
$Output = $ini_file.($a_section).($b_node) | Out-File $Store\Value.cmd
}
#---------------------------------------------------------------#
Function Write-File
{
Param(
[parameter(mandatory=$true)]$FilePath,
[parameter(mandatory=$true)] $a,
[parameter(mandatory=$true)] $b,
[parameter(mandatory=$true)] $c
)
Import-Module PsIni
$ff = Get-IniContent $FilePath
$ff["$a"]["$b"] = "$c"
$ff | Out-IniFile -FilePath $FilePath -Force
}
$cmd, $params = $args
& $cmd @params