簡體   English   中英

powershell腳本從txt讀取參數

[英]powershell script reading parameters from txt

我有一個腳本,需要2個參數(名稱和位置)。 我把名稱和位置放在一個txt文件中,根據這篇文章來自文件的Powershell參數 我被提示為第二個參數輸入值:

Import-Csv 'C:\temp\paramtest.txt' | % { C:\temp\script\paramtest.ps1 @_ }

命令管道位置1的cmdlet paramtest.ps1以下參數的供應值:param2:**

這就是我的.txt看起來像:

"param","param2"
"foo","c:\temp"
"bar","c:\temp"
"foobar","c:\temp"

而Powershell腳本很簡單:

Param (
    [Parameter(mandatory=$true,Position=1)]
    [string]$param, 
    [Parameter(mandatory=$true,Position=2)]
    [string]$param2
    ) 

$greeting='Hello to ' + $param + ' and ' + $param2
Write-Output $greeting

任何幫助表示贊賞。

使用Import-Csv cmdlet導入文件時,將返回PSCustomObject類型的對象。

splatting運算符( @需要哈希表,而不是PSCustomObject


PowerShell 3.0+

要從txt文件導入參數,可以使用ConvertFrom-StringData cmdlet將它們作為哈希表返回:

Get-Content -Path .\test.txt -ReadCount 2 | ForEach-Object {
    $Splat = ConvertFrom-StringData $($_ -join [Environment]::NewLine)
    .\paramtest.ps1 @Splat
}

並格式化您的文本文件,如下所示:

的text.txt

param=foo
param2=c:\\temp
param=bar
param2=c:\\temp
param=foobar
param2=c:\\temp

PowerShell 2.0

如果您正在使用PowerShell 2.0,或者您需要保留csv格式,則可以通過將PSCustomObject的值重新添加到新的哈希表中來自行完成工作,並執行以下操作:

Import-Csv .\test.txt |ForEach-Object {
    $Splat = @{}
    $_.psobject.Properties |ForEach-Object { $Splat[$_.Name] = $_.Value }
    .\paramtest.ps1 @Splat
}

暫無
暫無

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

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