Powershell脚本从txt读取参数 [英] powershell script reading parameters from txt
问题描述
我有一个接受2个参数(名称和位置)的脚本.我根据这篇文章的文件中的Powershell参数将名称和位置放入txt文件中.我被提示输入第二个参数的值:
I have a script that takes 2 parameters (name and location). I put the name and location into a txt file as per this post here Powershell parameters from file. I got prompted to put in value for the 2nd parameter:
Import-Csv 'C:\temp\paramtest.txt' | % { C:\temp\script\paramtest.ps1 @_ }
命令管道位置1上的cmdlet paramtest.ps1为以下项提供值 以下参数:param2:**
cmdlet paramtest.ps1 at command pipeline position 1 Supply values for the following parameters: param2:**
这是我的.txt的样子:
This is what my .txt look like:
"param","param2"
"foo","c:\temp"
"bar","c:\temp"
"foobar","c:\temp"
Powershell脚本很简单:
and the Powershell script is just plain:
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
类型的对象.
When you import the file with Import-Csv
cmdlet, you get objects of type PSCustomObject
back.
splating运算符(@
)需要哈希表,而不是PSCustomObject
.
To import the parameters from the txt file, you could use ConvertFrom-StringData
cmdlet to return them as hashtables instead:
Get-Content -Path .\test.txt -ReadCount 2 | ForEach-Object {
$Splat = ConvertFrom-StringData $($_ -join [Environment]::NewLine)
.\paramtest.ps1 @Splat
}
并像这样格式化文本文件:
And format your text file like this:
param=foo
param2=c:\\temp
param=bar
param2=c:\\temp
param=foobar
param2=c:\\temp
PowerShell 2.0
如果您使用的是PowerShell 2.0,或者需要保留csv格式,则可以通过将PSCustomObject
中的值引用到新的哈希表中并执行以下操作来自己完成这项工作:
PowerShell 2.0
If you are working with PowerShell 2.0, or if you need to retain the csv format, you can do the work yourself by refencing the values from PSCustomObject
into a new hashtable and splat that:
Import-Csv .\test.txt |ForEach-Object {
$Splat = @{}
$_.psobject.Properties |ForEach-Object { $Splat[$_.Name] = $_.Value }
.\paramtest.ps1 @Splat
}
这篇关于Powershell脚本从txt读取参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!