So I'm still fairly new to Powershell and I'm trying to write a script that allows the user to select a file or folder and then get back the security permissions for said folder/file. The problem is, I can't seem to get the file path to record as a variable to be used later. Here's what I have so far:
Function Get-Folder($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
$foldername = New-Object System.Windows.Forms.FolderBrowserDialog
$foldername.rootfolder = "MyComputer"
$foldername.ShowDialog()
if($foldername.ShowDialog() -eq "OK") {
$folder += $foldername.SelectedPath
}
}
Maybe I'm way off on this, but it will pull up the window to select a file or folder and makes me choose twice and then doesn't set the variable as the file path. Again, I'm pretty new to this kind of thing so I could be totally wrong, but any help would be incredibly helpful.
Thanks!
The folder selector window shows twice because you have two calls to $foldername.ShowDialog()
. Remove the first one, and leave only the one inside if
.
I tried to run your code, and am sure that $folder
variable is in fact set. If you think that it is not set you are doing something wrong. For example, be aware, that it is only visible inside your Get-Folder
function. If you need to use it outside of the function, you should return it (return $folder
) and assign it to a variable outside the function. For example:
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"
if($foldername.ShowDialog() -eq "OK")
{
$folder += $foldername.SelectedPath
}
return $folder
}
$a = Get-Folder
This way you will have your selected folder in the $a
variable.
You need to add " | Out-Null" to the end of the line
"[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")"
otherwise there is a bunch of info returned by Get-Folder you don't want
Cheers, Garth