Powershell – Read file with parameters as parameter in powershell script

powershellscripting

I have tried to do a powershell script the reads a file with parameters:

File with parameters (params.ini):

[domain]
domain="google.com"
[port]
port="80"

Powershell script that reads the file:

Get-Content "params.ini" | ForEach-Object -Begin {$settings=@{}} -Process {$store = [regex]::split($_,'='); if(($store[0].CompareTo("") -ne 0) -and ($store[0].StartsWith("[") -ne $True) -and ($store[0].StartsWith("#") -ne $True)) {$settings.Add($store[0], $store[1])}}

$Param1 = $settings.Get_Item("domain")
$Param2 = $settings.Get_Item("port")

# Displaying the parameters
Write-Host "Domain: $Param1";
Write-Host "Port: $Param2";

But I want the file to be read by parameter. For example:

> scriptExample.ps1 -file C:\params.ini

What changes should I apply?

Best Answer

So you need to handle Arguments.

$file contains the -file argument value that you will use within your script.


Non mandatory Argument :

Param(
  [string]$file
)

Mandatory Argument :

Param(
  [parameter(mandatory=$true)][string]$file
)

Full code (using mandatory argument) :

Param(
  [parameter(mandatory=$true)][string]$file
)

Get-Content "$file" | ForEach-Object -Begin {$settings=@{}} -Process {$store = [regex]::split($_,'='); if(($store[0].CompareTo("") -ne 0) -and ($store[0].StartsWith("[") -ne $True) -and ($store[0].StartsWith("#") -ne $True)) {$settings.Add($store[0], $store[1])}}

$Param1 = $settings.Get_Item("domain")
$Param2 = $settings.Get_Item("port")

# Displaying the parameters
Write-Host "Domain: $Param1";
Write-Host "Port: $Param2";

.\scriptExample.ps1 -file params.ini
Domain: "google.com"
Port: "80"