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 ($ in $path)
        $a = $

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.


Here's another option using a pipeline:

$arr = Get-ChildItem \\QNAP\wpbackup | 
       Where-Object {$_.PSIsContainer} | 
       Foreach-Object {$_.Name}

For completeness, and readability:

This get all files in "somefolder" starting with 'F' to an array.

$FileNames = Get-ChildItem -Path '.\somefolder\' -Name 'F*' -File

This gets all directories of current directory:

$FileNames = Get-ChildItem -Path '.\' -Directory

$array = (dir *.txt).FullName

$array is now a list of paths for all text files in the directory.

# initialize the items variable with the
# contents of a directory

$items = Get-ChildItem -Path "c:\temp"

# enumerate the items array
foreach ($item in $items)
      # if the item is a directory, then process it.
      if ($item.Attributes -eq "Directory")
            Write-Host $item.Name//displaying

            $array=$item.Name//storing in array


I believe the problem is that your foreach loop variable is $ What you want is a loop variable named $item, and you will access the name property on each one.


foreach ($item in $path)

Also take note that I've left $ unassigned. In Powershell, if the result isn't stored in a variable, piped to another command, or otherwise captured, it is included in the function's return value.

Need Your Help

Can a Regex Return the Number of the Line where the Match is Found?

regex replace find editor

In a text editor, I want to replace a given word with the number of the line number on which this word is found. Is this is possible with Regex?

How do I create a user-defined literal for a signed integer type?

c++ c++11

As I discovered from this post the parameter types allowed for a user-defined literal type are as follows: