创建Powershell脚本以获取网络文件夹信息捕获和显示LastWriteTime时出现问题

创建Powershell脚本以获取网络文件夹信息捕获和显示LastWriteTime时出现问题,powershell,Powershell,好吧,我不是程序员,我的Powershell经验是基本的。但事情是这样的。我被要求收集一些关于我们正在从网络上迁移的目录的信息。 它收集文件和文件夹的子目录名称、大小、日期戳并导出为csv。 我一辈子都不能让文件夹创建日期起作用,所以我放弃了,一直在寻找文件夹的lastwritetime,因为我正试图弄清楚最近使用了什么。它仅适用于少数文件夹,但excel中的其余文件夹的单元格中有system.object[]。非常令人沮丧。 这是代码。它使用gui目录选择器 #Refresh netw

好吧,我不是程序员,我的Powershell经验是基本的。但事情是这样的。我被要求收集一些关于我们正在从网络上迁移的目录的信息。 它收集文件和文件夹的子目录名称、大小、日期戳并导出为csv。 我一辈子都不能让文件夹创建日期起作用,所以我放弃了,一直在寻找文件夹的lastwritetime,因为我正试图弄清楚最近使用了什么。它仅适用于少数文件夹,但excel中的其余文件夹的单元格中有system.object[]。非常令人沮丧。 这是代码。它使用gui目录选择器

    #Refresh network drives for session
    net use i: /delete
    net use m: /delete
    net use i: "\\wfs.queensu.ca\ADV\Workgroups"
    net use m: "\\wfs.queensu.ca\ADVMedia"


    Function Get-Folder($initialDirectory)

    {
    [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")|Out-Null

    $foldername = New-Object System.Windows.Forms.FolderBrowserDialog
    $foldername.Description = "Select a folder"
    $foldername.rootfolder = "MyComputer"

    if($foldername.ShowDialog() -eq "OK")
    {
    $folder += $foldername.SelectedPath
    }
     return $folder
    }

    $forDir = Get-Folder

   #Change this to the parent directory that you want counts for
   #$forDir = "\\wfs.queensu.ca\adv\workgroups\ADV Services\$seldir"

   $Dirs = Get-ChildItem $forDir -Directory -Name

   $Tab = [char]9
   $results = @()

   Write-Host $forDir


   foreach($Dir in $Dirs)
   {
   $dirSize = "{0:N2} MB" -f ((Get-ChildItem $forDir/$Dir -Recurse | Measure-Object -Property Length 
   -Sum -ErrorAction Stop).Sum / 1MB)
   $dirFiles = Get-ChildItem $forDir/$Dir -Recurse -File | Measure-Object | %{$_.Count}
   $dirFolders = Get-ChildItem $forDir/$Dir -Recurse -Directory | Measure-Object | %{$_.Count}
   #$dirDate = (Get-ChildItem $forDir/$Dir).LastWriteTime.ToString
   $dirDate = @(Get-ChildItem $forDir/$Dir | % {$_.LastWriteTime})



   $details = [ordered] @{
   dir = $Dir
   No_Files = $dirFiles
   No_Folders = $dirFolders
   size = $dirSize
   date = $dirDate
   }

   $results += New-Object PSobject -Property $details


   }


  #This line finds the last index of the slash and adding one char
  $Dirlength = $forDir.LastIndexOf('\') + 1
  #This line takes the entire length of the string minus the postion above leaving the directory name 
  $sublength = $forDir.length - $Dirlength
  #Assigns the remaining characters from the substring to the varibale to be used as the filename
  $DirName = $forDir.SubString($Dirlength, $sublength)

  $results | Export-Csv "C:\$DirName.csv"  -NoTypeInformation

  Write-Host ("Complete WOW!")
Get ChildItem。\dir提供目录中包含的所有文件。\dir不是目录本身

这就是为什么脚本中的以下行为foreach循环中$forDir/$Dir解析到的目录中包含的所有文件创建LastWriteTimes数组的原因:

$dirDate = @(Get-ChildItem $forDir/$Dir | % {$_.LastWriteTime})
$dirDate中的数组将返回​调用其toString方法时,System.Object[]。这就是为什么您会在excel中看到这个字符串的原因,您希望看到文件夹的时间戳

我敢打赌,那些似乎有效的文件夹确实有一个子项

要获取目录本身的LastWriteTime,请使用get Item而不是get ChildItem

试试这个

Get-ChildItem -Path 'D:\temp' -Recurse | 
Where-Object { $_.PSIsContainer } | 
Select-Object -Property Name, LastWriteTime
<#
# Results

Name             LastWriteTime     
----             -------------     
est              17-Feb-20 15:50:53
LogFiles         11-Mar-20 11:37:28
NewFolder        06-Feb-20 14:56:48
ParentFolder     12-Feb-20 14:24:25
Reference        03-Feb-20 11:55:47
Source           06-Feb-20 14:56:48
Target           24-Feb-20 22:03:56
New folder       03-Feb-20 11:55:24
temp             20-Jan-20 11:17:42
ChildFolder      12-Feb-20 14:08:11
GrandchildFolder 12-Feb-20 14:08:32
#>


# Or in v3 and beyond

Get-ChildItem -Path 'D:\temp' -Directory -Recurse | 
Select-Object -Property Name, LastWriteTime
<#
# Results

Name             LastWriteTime     
----             -------------     
est              17-Feb-20 15:50:53
LogFiles         11-Mar-20 11:37:28
NewFolder        06-Feb-20 14:56:48
ParentFolder     12-Feb-20 14:24:25
Reference        03-Feb-20 11:55:47
Source           06-Feb-20 14:56:48
Target           24-Feb-20 22:03:56
New folder       03-Feb-20 11:55:24
temp             20-Jan-20 11:17:42
ChildFolder      12-Feb-20 14:08:11
GrandchildFolder 12-Feb-20 14:08:32
#>

我知道这个问题已经得到了回答,但为了完整起见,这里有另一种方法,即利用每个DirInfo对象拥有的方法

$rootFolder = 'X:\YourRootPath'
Get-ChildItem -Path $rootFolder -Directory -Recurse | ForEach-Object {
    # GetFileSystemInfos() (needs .NET 4+) is faster than Get-ChildItem and returns hidden objects by default
    # See: https://devblogs.microsoft.com/powershell/why-is-get-childitem-so-slow/
    $fsObjects = $_.GetFileSystemInfos('*', 'TopDirectoryOnly')   # TopDirectoryOnly --> do not recurse

    # you can also use Get-ChildItem here of course.
    # To also get hidden files, with Get-ChildItem you need to add the -Force switch
    # $fsObjects = Get-ChildItem -Path $_.FullName -Filter '*' -Force

    # from the $fsObjects array, filter out the files and directories in order to get the count
    $files   = $fsObjects | Where-Object { $_ -is [System.IO.FileInfo] }       # or: !($_.Attributes -band 'Directory')
    $folders = $fsObjects | Where-Object { $_ -is [System.IO.DirectoryInfo] }  # or: $_.Attributes -band 'Directory'
    # emit a PSObject with all properties you wish to collect
    [PsCustomObject]@{
        Path      = $_.FullName
        FileCount = $files.Count
        DirCount  = $folders.Count
        DirSize   = "{0:N2} MB" -f (($files | Measure-Object -Sum -Property Length).Sum / 1MB)
        DirDate   = $_.LastWriteTime
    }
} | Export-Csv -Path "X:\YourFolder_Info.csv" -NoTypeInformation -UseCulture

Manuel-Get ChildItem在这个用例中有一个“-File”和“-Directory”开关。谢谢!所有这些答案都很棒。将其从get childitem更改为get item使其立即工作。如果有问题,我将进一步测试并发回。您可以不用$forDir\$Dir,而只使用$Dir.FullName,它将为您提供完整的路径。
$rootFolder = 'X:\YourRootPath'
Get-ChildItem -Path $rootFolder -Directory -Recurse | ForEach-Object {
    # GetFileSystemInfos() (needs .NET 4+) is faster than Get-ChildItem and returns hidden objects by default
    # See: https://devblogs.microsoft.com/powershell/why-is-get-childitem-so-slow/
    $fsObjects = $_.GetFileSystemInfos('*', 'TopDirectoryOnly')   # TopDirectoryOnly --> do not recurse

    # you can also use Get-ChildItem here of course.
    # To also get hidden files, with Get-ChildItem you need to add the -Force switch
    # $fsObjects = Get-ChildItem -Path $_.FullName -Filter '*' -Force

    # from the $fsObjects array, filter out the files and directories in order to get the count
    $files   = $fsObjects | Where-Object { $_ -is [System.IO.FileInfo] }       # or: !($_.Attributes -band 'Directory')
    $folders = $fsObjects | Where-Object { $_ -is [System.IO.DirectoryInfo] }  # or: $_.Attributes -band 'Directory'
    # emit a PSObject with all properties you wish to collect
    [PsCustomObject]@{
        Path      = $_.FullName
        FileCount = $files.Count
        DirCount  = $folders.Count
        DirSize   = "{0:N2} MB" -f (($files | Measure-Object -Sum -Property Length).Sum / 1MB)
        DirDate   = $_.LastWriteTime
    }
} | Export-Csv -Path "X:\YourFolder_Info.csv" -NoTypeInformation -UseCulture