LightningJack
LightningJack

Reputation: 89

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

$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?

Upvotes: 0

Views: 185

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174435

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

Upvotes: 2

Related Questions