Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing Directory Folder Names Into Array Powershell

I am trying to write a script that will get the names of all the folders in a specific directory and then return each as an entry in an array. From here I was going to use each array element to run a larger loop that uses each element as a parameter for a later function call. All of this is through powershell.

At the moment I have this code:

function Get-Directorys
{
    $path = gci \\QNAP\wpbackup\

    foreach ($item.name in $path)
    {
        $a = $item.name
    }
}   

The $path line is correct and gets me all of the directories, however the foreach loop is the problem where it actually stores the individual chars of the first directory instead of each directories full name to each element.

like image 842
Jingles177 Avatar asked Dec 22 '12 00:12

Jingles177


People also ask

How do I get a list of folders in PowerShell?

On a Windows computer from PowerShell or cmd.exe, you can display a graphical view of a directory structure with the tree.com command. To get a list of directories, use the Directory parameter or the Attributes parameter with the Directory property. You can use the Recurse parameter with Directory.

How do you store values in an array in PowerShell?

To create and initialize an array, assign multiple values to a variable. The values stored in the array are delimited with a comma and separated from the variable name by the assignment operator ( = ). The comma can also be used to initialize a single item array by placing the comma before the single item.

How do I list files and folders in PowerShell?

If you want to list files and directories of a specific directory, utilize the “-Path” parameter in the “Get-ChildItem” command. This option will help PowerShell list all the child items of the specified directory. The “-Path” parameter is also utilized to set the paths of one or more locations of files.

How do I declare a string array in PowerShell?

PowerShell array of strings is the collection of string objects that is multiple strings are residing into the same collection which can be declared using String[], @() or the ArrayList and can be used in various ways like functions, in the file content, as a variable and can perform the multiple operations on the ...


1 Answers

Here's another option using a pipeline:

$arr = Get-ChildItem \\QNAP\wpbackup | 
       Where-Object {$_.PSIsContainer} | 
       Foreach-Object {$_.Name}
like image 198
Shay Levy Avatar answered Sep 20 '22 05:09

Shay Levy