# encoding: ascii
# api: powershell
# title: PromptFor-File
# description: Function to prompt user for file path input. Can create a open file type dialog or a save file type dialog by either specifying either “Open” or “Save” for the -Type parameter. Either a file path string is returned or null if the user canceled the dialog.
# version: 0.1
# type: function
# author: anti121
# license: CC0
# function: PromptFor-File
# x-poshcode-id: 1985
# x-archived: 2017-03-31T03:20:03
# x-published: 2011-07-19T17:20:00
#
# Examples:
# Save dialog example:
# PromptFor-File -Filename YourDefaultFilename.txt -FileTypes txt,xml -RestoreDirectory -Title “Select save location” -Type save
# Open file dialog example:
# PromptFor-File -Filename YourDefaultFilename.xml -FileTypes xml -InitialDirectory $env:userprofile -Type open
#
function PromptFor-File 
{
	param
	(	
		[String] $Type = "Open",
		[String] $Title = "Select File",
		[String] $Filename = $null,
		[String[]] $FileTypes,
		[switch] $RestoreDirectory,
		[IO.DirectoryInfo] $InitialDirectory = $null
	)
	
	[void][System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
	
	if ($FileTypes)
	{
		$FileTypes | % {
			$filter += $_.ToUpper() + " Files|*.$_|"
		}
		$filter = $filter.TrimEnd("|")
	}
	else
	{
		$filter = "All Files|*.*"
	}
	
	switch ($Type)
	{
		"Open" 
		{
			$dialog = New-Object System.Windows.Forms.OpenFileDialog
			$dialog.Multiselect = $false
		}
		"Save"
		{
			$dialog = New-Object System.Windows.Forms.SaveFileDialog
		}
	}
	
	$dialog.FileName = $Filename
	$dialog.Title = $Title
	$dialog.Filter = $filter
	$dialog.RestoreDirectory = $RestoreDirectory
	$dialog.InitialDirectory = $InitialDirectory.Fullname
	$dialog.ShowHelp = $true
	
	if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK)
	{
		return $dialog.FileName
	}
	else
	{
		return $null
	}
}
