2
\$\begingroup\$

I have a power shell script that when run will prompt the user to:

  1. Select a folder location
  2. select a file name
  3. enter credentials

This then exports those credentials in a xml file. Although this requires 3 prompts to the user before is complete. Looking to find if there is a better way to approach this. For example, having a single prompt for the user.

###########################################################
# Create a file containing encrypted credentials
###########################################################

clear

Function Get-Folder($initialDirectory)
{
    #User selected folder location
    [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")|Out-Null

    $path = New-Object System.Windows.Forms.FolderBrowserDialog
    $path.Description = "Select a folder"
    $path.rootfolder = "MyComputer"

    if($path.ShowDialog() -eq "OK")
    {
        $location += $path.SelectedPath
    }

    #User selected file name
    [void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')

    $title = 'File Name'
    $msg   = 'Please enter your file name'

    $text = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title)

    #Open prompt for user to enter credentials and export to xml file
    Get-Credential | Export-Clixml "$location\Credentials-$text.xml"

}

Get-Folder
\$\endgroup\$
2
\$\begingroup\$
  • Instead of letting the user (1) choose a folder and (2) choose a file name, you can just present the user with a Save File Dialog. It also warns the user if he tries to overwrite an existing file.

  • If the user cancels one of your dialogs, you should cancel the script rather than continue with invalid data.


$dialog = New-Object System.Windows.Forms.SaveFileDialog
$dialog.FileName = "Credentials.xml"
$dialog.Filter = "XML files (*.xml)|*.xml|All files|*.*"

if ($dialog.ShowDialog() -ne "OK")
{
    exit
}

...

Get-Credential | Export-Clixml $dialog.FileName
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.