Search code examples
powershellpowershell-3.0

How to use SaveFileDialog while using out-file command in powershell 3.0


I'm having a problem getting my output code to work in powershell 3.0. I've looked all over and can't seem to find the answer. I want to use the SaveFileDialog to help output a file. This is part of a much larger code that asks the user if they want to export before it goes on. It is used to output the code from exchange. Below is the code I've got. It works but it has 2 dialog boxes that pop-up, can anyone shed some light on this?

[string]$Export = Read-Host "Would you like to export? [y/n]"
IF ($Export -eq "y")
    {
      Function Get-FileName($initialDirectory)
        {   
         [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
         Out-Null

         $SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog
         $SaveFileDialog.initialDirectory = $initialDirectory
         $SaveFileDialog.filter = “Text files (*.txt)|*.txt|All files (*.*)|*.*”
         $SaveFileDialog.ShowDialog() | Out-Null
         $SaveFileDialog.filename
        }

        Get-FileName -initialDirectory "%USERDATA%\desktop\"
        $Savefile = Get-Filename

get-mailboxfolderpermission -identity $Email":\" | ft foldername, User, AccessRights -AutoSize | out-file $Savefile -Append -Width 500
Foreach ($Folder in $folders)
    {
    $NormalizedFolder = $Folder.FolderPath.Replace("/","\")
    $NormalizedIdentity = $Email + ":" + $NormalizedFolder
    get-mailboxfolderpermission -identity $NormalizedIdentity | ft foldername, User, AccessRights -AutoSize | out-file $Savefile -Append -Width 500
    }
}

Solution

  • The answer is that you are calling the function twice in a row. Your line:

    Get-FileName -initialDirectory "%USERDATA%\desktop\"
    

    isn't setting some setting for the function, it's calling it, and specifying the initial directory. It isn't saving the response or doing anything with it, so the text should just be returned to the screen. Then right afterward your next line:

    $Savefile = Get-Filename
    

    calls the same function again, this time not specifying an initial directory, and saves the response in the $SaveFile variable.

    Remove the first Get-File -initialDirectory line, and add the -initialdirectory $env:UserProfile\Desktop to the $Savefile = line.

    Edit: Just thought I'd comment that it's fairly standard practice to place functions at the top of a script. That way they are processed first, and are readily available as needed through the entire script. Placing it inside a IF statement means that it may never load, and if you wanted to use it later in the script it wouldn't be there. There is usually no harm in moving it to the top and having it available in case it's needed later.