在powershell脚本中以参数作为参数读取文件

use*_*911 3 scripting powershell

我试图做一个powershell脚本来读取一个带有参数的文件:

带有参数 ( params.ini) 的文件:

[domain]
domain="google.com"
[port]
port="80"
Run Code Online (Sandbox Code Playgroud)

读取文件的 Powershell 脚本:

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";
Run Code Online (Sandbox Code Playgroud)

但我希望通过参数读取文件。例如:

> scriptExample.ps1 -file C:\params.ini
Run Code Online (Sandbox Code Playgroud)

我应该应用哪些更改?

kri*_*sFR 5

所以你需要处理参数。

$file包含-file您将在脚本中使用的参数值。


非强制性参数:

Param(
  [string]$file
)
Run Code Online (Sandbox Code Playgroud)

强制性参数:

Param(
  [parameter(mandatory=$true)][string]$file
)
Run Code Online (Sandbox Code Playgroud)

完整代码(使用强制参数):

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";
Run Code Online (Sandbox Code Playgroud)
.\scriptExample.ps1 -file params.ini
Domain: "google.com"
Port: "80"
Run Code Online (Sandbox Code Playgroud)