在循环中填充对象并将整个数组输出为CSV

时间:2018-01-12 11:17:43

标签: arrays powershell loops csv export

我目前有一个脚本,它将运行一个文件夹并在里面打开每个PDF,然后会弹出一个输入框询问我要将文件重命名为。这部分工作正常但我正在尝试使用每个文件的信息填充数组,例如创建日期,修改日期,旧文件名和新文件名。

我目前的代码是:

Add-Type -AssemblyName Microsoft.VisualBasic 

$folderpath = 'file path'
$items = Get-ChildItem -Recurse $folderpath *.pdf
$newFileName = "" 
$counterID = 0
$amountOfScans = $items.Length
$typeOfScanner = ""

$scanArray = @()
$scanObject = New-Object System.Object

foreach( $i in $items)  {
    Start-Process ((Resolve-Path ("$folderpath$i")).Path)
    Start-Sleep -Seconds 1
    $counterID++ 

    $orderID = [Microsoft.VisualBasic.Interaction]::InputBox("Enter the new file name for scan $counterID / $amountOfScans :", $i)

    if ($newFileName -eq "delete"){
        $reasonForDeletion = [Microsoft.VisualBasic.Interaction]::InputBox("Enter a reason for marking $i for deletion :", $i)
    }

    if ($i.Length -eq 24){
        $typeOfScanner = "Xerox"
    }
    elseif ($ie.Length -eq 33) {
        $typeOfScanner = "Lexmark"
    }

    $DateCreated = Get-ItemProperty ((Resolve-Path ("$folderpath$i")).Path) | select -exp CreationTime
    $DateModified1 = Get-Date -Format dd/MM/yyyy        
    $DateModified2 = Get-Date -Format HH:mm:ss
    $DateModifiedTotal = ("$DateModified1 $DateModified2")

    $scanObject[$counterID] | Add-Member -type NoteProperty -name TempName -Value "$i" 
    $scanObject[$counterID] | Add-Member -type NoteProperty -name NewName -Value "$orderID"
    $scanObject[$counterID] | Add-Member -type NoteProperty -name TypeOfScanner -Value "$typeOfScanner"
    $scanObject[$counterID] | Add-Member -type NoteProperty -name DateCreated -Value "$DateCreated"
    $scanObject[$counterID] | Add-Member -type NoteProperty -name DateModified -Value "$DateModifiedTotal"
    $scanObject[$counterID] | Add-Member -type NoteProperty -name ReasonForDeletion -Value "$reasonForDeletion"

    $scanArray += $scanObject[$counterID]

    Stop-Process -Name "Acro*"
}

$scanArray | export-csv C:\Scans\renamed_stats.csv -notypeinformation

但是在运行此脚本后,“renamed_stats.csv”完全为空,没有错误消息。

任何帮助将不胜感激:)

2 个答案:

答案 0 :(得分:2)

尝试以这种方式在内部循环中创建$scanObject

$scanObject = New-Object PSObject -Property @{
    TempName = "$i"
    NewName = "$orderID"
    TypeOfScanner = "$typeOfScanner"
    DateCreated = "$DateCreated"
    DateModified = "$DateModifiedTotal"
    ReasonForDeletion = "$reasonForDeletion"
}

答案 1 :(得分:2)

假设你没有太多的对象而内存不足,并且你的值变量如$i包含了预期,你可以完全摆脱$scanObject并执行此操作:< / p>

[array]$scanArray += [PSCustomObject] @{
    TempName          = "$i"
    NewName           = "$orderID"
    TypeOfScanner     = "$typeOfScanner"
    DateCreated       = "$DateCreated"
    DateModified      = "$DateModifiedTotal"
    ReasonForDeletion = "$reasonForDeletion"
}

您还可以使用引号改进日期部分:

$DateModified = Get-Date -Format "dd/MM/yyyy HH:mm:ss"