How can I format my string to be recognized as a path in my PowerShell script?

The point of this odd little script is just to let me choose a directory and have whatever is in my clipboard written to a text file in that path. This path will unfortunately always contain parentheses, brackets, and sometimes braces.

Y:

Function Get-Folder($initialDirectory="")

{
    [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")|Out-Null

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

    if($foldername.ShowDialog() -eq "OK")
    {
        $folder += $foldername.SelectedPath
    }
    return $folder
}

$myFolder = Get-Folder('Y:\MyStuff (OtherStuff)')

Get-Clipboard > $myFolder\myFile.txt

Because of the brackets in the subfolder, I get this error message

out-file : Cannot perform operation because the wildcard path Y:\MyStuff
(OtherStuff)\Sub1\Sub2 [Info] [Some More Info]\myFile.txt did not resolve to a file.
At line:22 char:1
+ Get-Clipboard > $myFolder\myFile.txt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OpenError: (Y:\Music (MyStu...nfo]\myFile.txt:Stri 
   ng) [Out-File], FileNotFoundException
    + FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.OutF 
   ileCommand

No amount of -replace combinations to account for the escape characters using ' or \ has resulted in success. How can I format the string so it resolves to a real directory?

Second question Is there a way to select a path with the more user-friendly FileBrowserDialog instead of FolderBrowser where you can't type or paste in a path?



from Recent Questions - Stack Overflow https://ift.tt/3dYRTPH
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Spring Elasticsearch Operations

Network Error and Timeout on Authorize.net JS

Object oriented programming concepts (OOPs)