无法在PoweSshell中显示export-csv

问题描述

我一直在研究网络,以查看缺少什么并且找不到,我运行了通过计算机列表运行的命令,但是导出文档始终为空。

这是代码

    foreach ($computer in Get-Content "\\NETWORK PATH\user-computers.txt") {
    Write-host $computer
    $colDrives = Get-WmiObject Win32_MappedLogicaldisk -ComputerName $computer

    $Report = @()

    # Set our filename based on the execution time
    $filenamestring = "$computer-$(get-date -UFormat "%y-%b-%a-%H%M").csv"
    foreach ($objDrive in $colDrives) {
    # For each mapped drive – build a hash containing @R_471_4045@ion
    $hash = @{
    ComputerName = $computer
    MappedLocation = $objDrive.ProviderName
    DriveLetter = $objDrive.deviceid
    }
    # Add the hash to a new object
    $objDriveInfo = new-object PSObject -Property $hash
    # Store our new object within the report array
    $Report += $objDriveInfo
    }}
    # Export our report array to CSV and store as our dynamic file name
    $Report | Export-Csv -LiteralPath "\\NETWORK PATH\Drive-Maps.csv" -NoType@R_471_4045@ion

我想知道每台计算机当前都映射了哪些网络驱动器,谢谢您的所有帮助和指导。

解决方法

我不确定您为什么没有得到输出。由于某些原因,我已经重写了您的脚本。首先,您的变量命名不是很清楚。我猜您来自VBScripting背景。接下来,您要创建一个数组,然后添加到其中-完全不需要。您可以通过分配类似tihs来直接捕获任何循环/脚本块/等的输出。

$Report = foreach($thing in $manythings){Do lots of stuff and everything in stdout will be captured}

如果您以利用流水线的方式编写脚本,则可以做更多的事情。接下来,与使用V3中引入的New-Object类型的加速器相比,使用[PSCustomObject]创建对象的速度较慢。最后,似乎您为每台计算机创建了一个自定义的csv,但最终您只是将所有内容导出到一个文件中。我假设您要收集所有这些信息并放入一个CSV。

我为您提供的帮助您进行故障排除的建议是,请对您的计算机运行此操作并在屏幕上确认输出。您在屏幕上看到的所有内容都应捕获在report变量中。 (除写主机外,它很特殊,只是进入控制台)

$computerList = "\\NETWORK PATH\user-computers.txt"

$reportFile = "\\NETWORK PATH\Drive-Maps.csv"

Get-Content $computerList | ForEach-Object {
    Write-host $_
    $mappedDrives = Get-WmiObject Win32_MappedLogicalDisk -ComputerName $_

    foreach ($drive in $mappedDrives)
    {
        # For each mapped drive – build a hash containing information
        [PSCustomObject]@{
            ComputerName = $_
            MappedLocation = $drive.ProviderName
            DriveLetter = $drive.DeviceId
        }

    }
} -OutVariable Report

一旦您知道所有正确的信息,请运行此信息以将其导出。

$Report  | Export-Csv -LiteralPath $reportFile -NoTypeInformation