Powershell script parameters with txt
I have a script that takes 2 parameters (name and location). I put name and location in txt file as per this post here Powershell options from file . I was prompted to enter a value for the second parameter:
Import-Csv 'C:\temp\paramtest.txt' | % { C:\temp\script\paramtest.ps1 @_ }
cmdlet paramtest.ps1 at conveyor position of conveyor 1 Feed values ββfor the following parameters: param2: **
This is what my .txt looks like:
"param","param2" "foo","c:\temp" "bar","c:\temp" "foobar","c:\temp"
and the Powershell script is simple:
Param ( [Parameter(mandatory=$true,Position=1)] [string]$param, [Parameter(mandatory=$true,Position=2)] [string]$param2 ) $greeting='Hello to ' + $param + ' and ' + $param2 Write-Output $greeting
Any help is appreciated.
source to share
When you import the file using the cmdlet, Import-Csv
you return objects of type PSCustomObject
.
splatting ( @
) operator expects a hash table, not PSCustomObject
.
PowerShell 3.0+
To import parameters from a txt file, you can use a cmdlet ConvertFrom-StringData
to use hash tables instead:
Get-Content -Path .\test.txt -ReadCount 2 | ForEach-Object {
$Splat = ConvertFrom-StringData $($_ -join [Environment]::NewLine)
.\paramtest.ps1 @Splat
}
And format the text file like this:
text.txt
param=foo
param2=c:\\temp
param=bar
param2=c:\\temp
param=foobar
param2=c:\\temp
PowerShell 2.0
If you are working with PowerShell 2.0, or if you need to keep the csv format, you can do the job yourself by returning values ββfrom PSCustomObject
into a new hash table and splat, which are:
Import-Csv .\test.txt |ForEach-Object {
$Splat = @{}
$_.psobject.Properties |ForEach-Object { $Splat[$_.Name] = $_.Value }
.\paramtest.ps1 @Splat
}
source to share