Saving Directory Directory Names to a Powershell Array

I am trying to write a script that will get the names of all folders in a specific directory and then return each as an entry in an array. From here, I was going to use each element of the array to start a larger loop, which uses each element as a parameter for the subsequent function call. All this 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 correct and returns all the directories to me, however the foreach loop is a problem when it actually stores the individual characters of the first directory instead of the full name of each directory for each element.

+12
source share
5 answers

Here's another option using a pipeline:

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

For completeness and readability:

Get all the files in "some folder", starting from "F" to the array.

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

This gets all the directories of the current directory:

 $FileNames = Get-ChildItem -Path '.\' -Directory 
+5
source

$ array = (dir * .txt) .FullName

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

+4
source
 # 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 } } 
+4
source

I believe the problem is that your loop variable is foreach $item.name . What you want is a loop variable called $item , and you will get access to the name property for each of them.

those.

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

Also note that I left $item.name . In Powershell, if the result is not stored in a variable, redirected to another command, or otherwise committed, it is included in the return value of the function.

+2
source

All Articles