【问题标题】:Storing Directory Folder Names Into Array Powershell将目录文件夹名称存储到阵列 Powershell
【发布时间】:2012-12-09 13:02:51
【问题描述】:

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

目前我有这个代码:

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

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

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

【问题讨论】:

    标签: arrays powershell directory


    【解决方案1】:

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

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

    【讨论】:

    • 这是一个更完整的解决方案。应标记为答案。
    • 这个很有用,谢谢:| Foreach-对象 {$_.Name}
    • 就我而言,出于某种原因,这会将所有目录名称连接到一个字符串中。
    • 这里似乎也是一个字符串,虽然我需要一个数组。抱歉,我是 Powershell 新手...
    【解决方案2】:

    $array = (dir *.txt).FullName

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

    【讨论】:

      【解决方案3】:

      为了完整性和可读性:

      这会将“somefolder”中以“F”开头的所有文件放到一个数组中。

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

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

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

      【讨论】:

        【解决方案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
        
              }
        }
        

        【讨论】:

          【解决方案5】:

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

          即,

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

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

          【讨论】:

          • 非常感谢。我改为这个,然后将每个返回值分配给函数外部的一个 var。从这里我现在可以使用 $a[xxx] 来获得我想要的值。不知道您关于以这种方式返回非存储值的第二条评论。
          • 是的。这是一个让我难过一两次的小问题,尤其是因为当时我什至没有意识到我有未消耗的输出。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-10-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-29
          相关资源
          最近更新 更多