PowerShell脚本会计算许多服务器中的文件和文件夹,然后将输出导出到CSV文件

时间:2019-06-07 09:39:10

标签: powershell csv

我正在生成一个PowerShell脚本,该脚本接收一个远程服务器列表,并计算所述列表中每个服务器的每个驱动器上的所有文件和文件夹。似乎用于计数文件并导出到csv的代码可能已关闭。

以下是我开发的脚本的当前迭代:

#variable used to call the list of R servers
$ServerList = 'H:\R_SERVER_COUNT\AllServerNames.txt'

# Loops through all the servers on list
foreach ($server in Get-Content $ServerList) {
    $count = Get-ChildItem -r "$server\"

    $fcount = Get-WmiObject Win32-LogicalDisk -ComputerName '$server' |
              Select-Object @{Label="Server";Expression={$_.SystemName}},
                  @{Label="Drive";Expression={$_.DeviceID}},
                  @{Label="Files";Expression={($count | ? {$_.PSIsContainer -eq $false}).Count}},
                  @{Label="Folders";Expression={($count | ? {$_.PSIsContainer -eq $true}).Count}}
    $folderAndFileCount += $fcount
}

#creates a csv file and places it into folder
$folderAndFileCount |
    Export-Csv 'H:/R_SERVER_COUNT/FolderAndFileCount.csv' -NoTypeInformation -Encoding UTF8

我希望得到一个CSV文件,该文件提供服务器名称,驱动器名称,文件计数和文件夹计数。 目前我得到

1 个答案:

答案 0 :(得分:0)

虽然我认为robocopy可能会是一个更好的解决方案[通常至少快一个数量级],但这可以完成工作。请注意,我在测试时已-Recurse进行了注释。您需要重新启用该功能才能进行真实的操作。 [咧嘴]

这使用Invoke-Command在目标系统上并行运行。它会忽略非响应系统,但是如果需要它们,可以通过将输入列表与响应者进行比较来获取名称。

您可能还想使用Select-Object来删除Invoke-Command添加的通常不需要的属性[PSComputerName,RunspaceID等...]。

#requires -RunAsAdministrator

$ComputerNameList = @'
LocalHost
10.0.0.1
127.0.0.1
BetterNotBeThere
'@ -split [System.Environment]::NewLine

$IC_ScriptBlock = {
    $DriveList = Get-PSDrive -PSProvider 'FileSystem' |
        # exclude read-only devices such as ROM drives
        Where-Object {$_.Free -gt 0}

    foreach ($DL_Item in $DriveList)
        {
        $GCI_Params = @{
            LiteralPath = $DL_Item.Root
            # while testing, leave the "-Recurse" paramter out
            #Recurse =  $True
            ErrorAction = 'SilentlyContinue'
            Force = $True
            }
        $DF_Info = Get-ChildItem @GCI_Params
        $DirInfo = $DF_Info.Where({$_.PsIsContainer})
        [PSCustomObject]@{
            SystemName = $env:COMPUTERNAME
            Drive = $DL_Item.Root.Trim('\')
            DirCount = $DirInfo.Count
            FileCount = $DF_Info.Count - $DirInfo.Count
            }
        }
    }
$IC_Params = @{
    ComputerName = $ComputerNameList
    ScriptBlock = $IC_ScriptBlock
    ErrorAction = 'SilentlyContinue'
    }
$RespondingSystems = Invoke-Command @IC_Params

$RespondingSystems

来自一个系统的一个驱动器...

SystemName     : [MySysName]
Drive          : C:
DirCount       : 13
FileCount      : 3
PSComputerName : LocalHost
RunspaceId     : 0c67f714-ae8a-4831-b647-b27bd73ce94d