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?
Get-Folder Y:\MyStuff (OtherStuff)'
- not like C# methods -Get-Folder('Y:\MyStuff (OtherStuff)')
; seeGet-Help about_Parsing
. If you use,
to separate arguments, you'll construct an array that a function sees as a single argument. To prevent accidental use of method syntax, use `Set-StrictMode -Version 2 or higher, but note that this places additional constraints on your code. – mklement0