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!
You can also change directory in PowerShell to a specified path. To change directory, enter Set-Location followed by the Path parameter, then the full path you want to change directory to. If the new directory path has spaces, enclose the path in a double-quote (“”).
Use the Read-Host to Prompt for User Input in PowerShell The -Prompt parameter is used to specify a text to provide the information about what to input. It appends a colon : to the text you enter. The Read-Host pauses execution and receives input. When a user enters the value at the prompt, it returns that same value.
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"
$foldername.SelectedPath = $initialDirectory
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With