使用Powershell

时间:2019-01-10 18:38:45

标签: powershell

此代码的目的是将文件从一个位置传输到另一位置,并记录传输是成功还是失败。

一切正常,除了日志出现问题。我希望日志为CSV格式,并有3列:成功/失败,从位置到位置。这会将结果全部输出到一列的行中。

我尝试了Export-Csv选项,但是它会查找对象/属性,因此仅显示长度(我也有字符串)。添加内容有效,但只有一列。有什么建议么?

#LOCATION OF CSV
$csv = Import-Csv C:\test2.csv
#SPECIFY DATE     (EXAMPLE-DELETE FILES > 7 YEARS.  7 YEARS=2555 DAYS SO YOU WOULD ENTER "-2555" BELOW)
$Daysback = "-1"
#FILE DESTINATION
$storagedestination = "C:\Users\mark\Documents\Test2"
#LOG LOCATION
$loglocation = "C:\Users\mark\Documents\filetransferlog.csv"
$s = "SUCCESS"
$f = "FAIL"


$CurrentDate = Get-Date
foreach ($line in $csv) {
    $Path = $line | Select-Object -ExpandProperty FullName
    $DatetoDelete = $CurrentDate.AddDays($DaysBack)

    $objects = Get-ChildItem $Path -Recurse | Select-Object FullName, CreationTime, LastWriteTime, LastAccessTime | Where-Object { $_.LastWriteTime -lt $DatetoDelete } 

    foreach ($object in $objects) {
        try 
        {
            $sourceRoot = $object | Select-Object -ExpandProperty FullName
            Copy-Item -Path $sourceRoot -Recurse -Destination $storagedestination 
            Remove-Item -Path $sourceRoot -Force -Recurse
            $temp = $s, $sourceRoot, $storagedestination
            $temp | add-content $loglocation
        }
        catch
        {
            $temp2 = $f, $sourceRoot, $storagedestination
            $temp2 | add-content $loglocation
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您所有的render都是多余的,只需将属性名称附加到变量名称=> | Select-Object -ExpandProperty
为什么每次都要在foreach中计算$Path = $line.FullName
将成功/失败输出到[PSCustomObject],并将它们收集到直接分配给foreach的变量中。

未经测试:

$DatetoDelete