Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Powershell: How can I get the UNC path from an OpenFileDialog without the leaf?

I’m still a beginner in Powershell…
I’m using the OpenFileDialog to give the user the possibility to choose a file on the network.

Add some .net Assembly for OpenFileDialog and MessageBox

Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName PresentationFramework

This is the OpenFileDialog-Definition

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog

With this the OpenFileDialog will be opened and shown to the user for choosing a file

$null = $FileBrowser.ShowDialog()

This is the UNC-filename with extension included that the user has chosen in OpenFileDialog

$full_filename = $FileBrowser.FileName

This is only the filename with extension (leaf) that the user has chosen in OpenFileDialog

$filename = $FileBrowser.SafeFileName

This converts the array-elements into strings

$full_filename_string = [string]$full_filename
$filename_string = [string]$filename

So far, so good.
What I would need additionally is the UNC-path ONLY from the subdirectory, in which the user has chosen a file (UNC-path without the leaf).

How could this be accomplished?

>Solution :

Use the Split-Path cmdlet:

PS ~> '\\hostname\share\path\to\directory\with_file.exe' |Split-Path -Parent
\\host\share\path\to\directory

Beware that the Split-Path will convert \ to / on linux file systems, to avoid that you’d have to manually split the string on the last occurrence of \:

PS ~> $path,$name = '\\hostname\share\path\to\directory\with_file.exe' -split '\\(?=[^\\]*$)'
PS ~> $path
\\hostname\share\path\to\directory
PS ~> $name
with_file.exe
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading