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

Jin*_*177 13 arrays directory powershell

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

目前我有这个代码:

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

    foreach ($item.name in $path)
    {
        $a = $item.name
    }
}   
Run Code Online (Sandbox Code Playgroud)

$ path行是正确的并且获取了所有目录,但foreach循环是它实际存储第一个目录的各个字符而不是每个directorys全名到每个元素的问题.我已经对Powershell如何创建数组做了一些研究,但我有点困惑,所以我希望有人能指出我正确的方向.

谢谢你的帮助.

Sha*_*evy 24

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

$arr = Get-ChildItem \\QNAP\wpbackup | 
       Where-Object {$_.PSIsContainer} | 
       Foreach-Object {$_.Name}
Run Code Online (Sandbox Code Playgroud)


小智 8

$array = (dir *.txt).FullName

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


小智 6

# 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

      }
}
Run Code Online (Sandbox Code Playgroud)


Gom*_*shi 5

为了完整性和可读性:

这将以"F"开头的"somefolder"中的所有文件到达数组.

$FileNames = Get-ChildItem -Path '.\somefolder\' -Name 'F*' -File
Run Code Online (Sandbox Code Playgroud)

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

$FileNames = Get-ChildItem -Path '.\' -Directory
Run Code Online (Sandbox Code Playgroud)