【问题标题】:Powershell counting files on network location, different output when running Powershell vs the ISE网络位置上的 Powershell 计数文件,运行 Powershell 与 ISE 时的不同输出
【发布时间】:2015-09-28 16:30:27
【问题描述】:

我正在编写一个 Powershell 脚本来计算 2 个网络路径的每个子目录中的文件数。当我在 ISE Debug 中运行它时,我的脚本运行良好,但是当我尝试运行它时,Powershell 输出被截断并且它不提供计数。我很确定这是因为我在错误的位置关闭了 foreach,但我似乎无法弄清楚这一点。我对 Powershell 很陌生。

$dirs = "\\myserver\myshare\directory1" , "\\myserver\myshare\directory2"
$txt = "\\myserver\myshare\output.txt"

ForEach ($dir in $dirs)
    {
    (Get-ChildItem $dirs -recurse -Directory | ForEach-Object{
      $props = @{
         Folder = $_.FullName
         Count = (Get-ChildItem -Path $_.Fullname -File | Measure-    Object).Count
                }
New-Object PSObject -Property $props } | Select-Object Folder , Count) |   Format-Table -AutoSize | Out-File $txt
} 

【问题讨论】:

    标签: powershell foreach scripting


    【解决方案1】:

    两件事:

    1. Get-ChildItem 应该是 $dir 而不是 $dirs
    2. 您的格式表应包含字段名称。
    $dirs = "\\myserver\myshare\directory1", "\\myserver\myshare\directory2"
    $txt = "\\myserver\myshare\output.txt"
    
    ForEach ($dir in $dirs)
    {
        (Get-ChildItem $dir -recurse -Directory | ForEach-Object {
          $props = @{
             Folder = $_.FullName
             Count = (Get-ChildItem -Path $_.Fullname -File | Measure-Object).Count
                    }
    New-Object PSObject -Property $props } | Select-Object Folder, Count) | Format-Table -AutoSize -property Folder, Count | Out-File $txt
    }
    

    我相信 #2 是因为 Format-Table 假设 PS 窗口的宽度为最大线宽。如果 ISE 窗口为全屏,则 PS 窗口的宽度大于独立 PS 窗口的默认设置。

    【讨论】:

      【解决方案2】:

      谢谢,我现在有这个工作。我仍然必须使用 Get-ChildItem $Dirs,通过使用 Dir 它只将其中一个路径写入 csv 文件。但是,我确实根据您的建议使用了 Format-Table,但我将 -Autosize 更改为 -wrap。

      $dirs= ""\\myserver\myshare\directory1","\\myserver\myshare\directory2"                                                                                                           
      $txt = "\\myserver\myshare\output.txt"
      
      ForEach ($dir in $dirs)
      {
      (Get-ChildItem $dirs -recurse -Directory | ForEach-Object {
        $props = @{
           Folder = $_.FullName
           Count = (Get-ChildItem -Path $_.Fullname -File | Measure-Object).Count
                  }
      New-Object PSObject -Property $props } | Select-Object Folder, Count) |Format-Table -Wrap -property Folder, Count | Out-File $txt
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-23
        • 2019-02-26
        • 1970-01-01
        • 1970-01-01
        • 2022-06-23
        • 2017-04-17
        • 2012-03-09
        • 1970-01-01
        相关资源
        最近更新 更多