Quantcast
Channel: QuickTip – Jaap Brasser's Blog
Viewing all articles
Browse latest Browse all 18

Quicktip: Use a Csv file to splat parameters into a function

$
0
0

I recently received a question on Reddit that asked if it is possible to use a csv file to create a hash table that can be used for splatting parameters into a function. The goal of this exercise is to be able to specify a csv file and to pass on the proper arguments to a function.

For example there is a csv file with the following contents:

SplatCsv

So based on this the New-Server function should be called as such:

1
New-Server -Templare 2012R2 -Spec DomainJoinSpec -Datastore Production2 -Cpus 1

In order to achieve this, the first step would be to remove the empty fields from the equasion as such:

1
2
$Csv = Import-Csv -Path Parameters.csv
$Csv.psobject.Properties | Where-Object {$_.Value}

This will import the csv and only display the colums in the csv that actually contain data. To ensure this data is stored in a hash table we can use the ForEach-Object. This cmdlet can be used to loop through the remaining results and to create a hashtable:

1
2
3
4
5
6
$Csv = Import-Csv c:\temp\params.csv
$Csv.psobject.Properties | Where-Object {$_.Value} | ForEach-Object -Begin {
$SplatParams = @{}
} -Process {
$SplatParams[$_.Name] = $_.Value
}

Now that the hash table has been created this can be used for splatting into the New-Server function:

1
New-Server @SplatParams

By combining the ForEach-Object cmdlet and the PSObject property that is piped into Where-Object it is possible to construct a custom hashtable that can be used for splatting. This can provide an easy alternative for non-technical users to provide parameters and arguments into a PowerShell function.

TwitterLinkedInFacebookGoogle+RedditWordPressEmailTumblrPinterestHacker NewsShare


Viewing all articles
Browse latest Browse all 18

Trending Articles