如何通过 streamwriter 将信息写入 .csv 文件

How to write information to .csv file via streamwriter

我正在尝试使用 powershell 脚本将大量信息写入 .csv 文件。我在 1500 台计算机上 运行 这个脚本来自 SCCM 配置管理器中的 "Run Script" 功能。该脚本在所有机器上运行,但并非所有机器都在文件中写入有关它们的信息。在 1352 台机器中,只有 375 台写入了文件。我怀疑该程序要么 运行 太快,无法在下一台机器运行脚本之前打开和关闭文件,并且无法写入文件,因为它仍然打开。有什么想法可以解决这个问题吗?我看过有关使用 StreamWriter 的帖子,但不确定是否能解决我的问题。

我试过将计算机分成更小的组,比如一次 8 个,但 8 个中只有 5 个将信息写入文件。代码在下面并且有效。

#Overrides GPO execution policy
Set-ExecutionPolicy Bypass


#Gets and writes computer name to .csv file
$env:COMPUTERNAME = HostName

#Checks the path to see if a particular file is present
$DeplPath = "AppData\LocalLow\Sun\Java\Deployment\deployment.properties"


#Checks each user profile on machine for the deployment.properties file and writes to .csv "True" if present and "False" if it isn't
$javausers = foreach ($User in Get-ChildItem C:\Users -Directory){
    $folder = Join-Path $User.FullName $DeplPath
    if (Test-Path $folder) {
        $TestResult = "True  - deployment.properties"
    } Else {
        $TestResult = "False - Path not found"
    }
    [PSCustomObject]@{
        "Computer Name" = $env:COMPUTERNAME 
        "Java User True/False"       = $TestResult
        "Users"         = $user.Name
        #"Last Write Time" = $file.LastWriteTime = (Get-Date)

    }
}

#This is used for on-screen display only
#$javausers

#Tests path accessibility and writes an error file to the local machine if the path can't be found
try
{
$javausers | Export-Csv -NoTypeInformation -Path "\anyserver\Java_User_Reports\testjava.csv" -Append

}
catch
{
$_| Out-File "c:\Temp\java_error.txt"

}

我希望将脚本正在搜索的有关每个用户的信息写入 1500 台机器中每台机器的文件。

我找到了一个更简单的解决方案,只需在文件名中添加一个 Get-Date 选项,这样 if 也可以缩短毫秒数,确保每次都创建一个新文件,而前一个文件会不被覆盖。这在几分钟内创建了 1365 个文件。我将输出行更改为以下内容:

$dateTime | Export-Csv -NoTypeInformation -Path "\anyserver\Java_User_Reports$env:COMPUTERNAME-javausers-$(Get-Date -Format "yyyyMMddHHmmssff").csv" -Append

然后我将文件复制到我机器上的本地文件夹,打开命令提示符,输入命令以更改文件所在的目录路径。然后我输入命令查看文件夹中的文件并确保我想要的所有文件都在那里。最后,我输入了 copy *.csv newfilenamehere.csv 这样所有的信息都会放在一个文件中。结果正是我所需要的,并解决了从多台计算机获取信息而脚本不保持文件打开且不允许向其写入其他信息的问题。