将目录文件夹名称存储到阵列Powershell中

时间:2012-12-22 00:04:47

标签: arrays powershell directory

我正在尝试编写一个脚本,该脚本将获取特定目录中所有文件夹的名称,然后将每个文件夹作为数组中的条目返回。从这里开始,我将使用每个数组元素来运行一个更大的循环,该循环使用每个元素作为稍后函数调用的参数。所有这一切都是通过powershell进行的。

目前我有这段代码:

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

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

$path行是正确的并且获取了所有目录,但是foreach循环是它实际存储第一个目录的各个字符而不是每个目录全名到每个元素的问题。

5 个答案:

答案 0 :(得分:22)

这是使用管道的另一个选项:

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

答案 1 :(得分:5)

为了完整性和可读性:

这将获取" somefolder"中的所有文件。从' F'开始到阵列。

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

这将获取当前目录的所有目录:

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

答案 2 :(得分:4)

$ array =(dir * .txt).FullName

$ array现在是目录中所有文本文件的路径列表。

答案 3 :(得分:4)

# 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 :(得分:2)

我认为问题是您的foreach循环变量为$item.name。你想要的是一个名为$item的循环变量,你将在每个变量上访问name属性。

即,

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

另请注意,我已将$item.name取消分配。在Powershell中,如果结果未存储在变量中,通过管道传输到另一个命令或以其他方式捕获,则它将包含在函数的返回值中。