this will do what you seem to want. however, it is a REALLY strange way to handle the problem. it is SLOW since it does a file write for every item OR a screen write for each item if that is enabled. saving to a $Var and then writing to file and/or screen would be much faster. [grin]
this code expands your last line into a ForEach-Object
call with an if
to test the output destination. it also adds an -ErrorAction
to the Get-ChildItem
call to handle "inaccessible file" errors.
it also removes the unneeded $()
in the expression =
lines.
$directory = $env:TEMP
$outpath = "$env:TEMP\GustavRasmussen.csv"
# uncomment the 2nd line to test the negative
$ToScreen = $True
#$ToScreen = $False
Get-ChildItem $directory -Recurse -File -ErrorAction SilentlyContinue |
Select-Object @{name='Folder_Name';expression={$_.directoryname}},
@{name='File_type';expression={$_.extension}},
@{name='File_name';expression={$_.name}},
@{name='File_size_bytes';expression={$_.length}},
@{name='Creation_datetime';expression={$_.creationtime}},
@{name='Last_update_datetime';expression={$_.lastwritetime}},
@{name='Last_read_datetime';expression={$_.lastaccesstime}} |
ForEach-Object {
if ($ToScreen)
{
$_
}
else
{
Export-Csv -InputObject $_ -path $outpath -NoTypeInformation -force -Delimiter ';' -Append
}
}
1st three lines of the CSV ...
"Folder_Name";"File_type";"File_name";"File_size_bytes";"Creation_datetime";"Last_update_datetime";"Last_read_datetime"
"C:\Temp";".tmp";"DELCD3A.tmp";"861968";"2019-07-13 11:43:18 PM";"2019-07-13 11:42:36 PM";"2019-07-13 11:43:18 PM"
"C:\Temp";".txt";"FXSAPIDebugLogFile.txt";"0";"2015-11-03 6:54:02 PM";"2015-11-03 6:54:02 PM";"2015-11-03 6:54:02 PM"
"C:\Temp";".log";"Genre-List_2019-10-01.log";"178";"2019-10-01 12:33:47 PM";"2019-10-01 12:33:47 PM";"2019-10-01 12:33:47 PM"
the 1st three items of the screen output ...
Folder_Name : C:\Temp
File_type : .tmp
File_name : DELCD3A.tmp
File_size_bytes : 861968
Creation_datetime : 2019-07-13 11:43:18 PM
Last_update_datetime : 2019-07-13 11:42:36 PM
Last_read_datetime : 2019-07-13 11:43:18 PM
Folder_Name : C:\Temp
File_type : .txt
File_name : FXSAPIDebugLogFile.txt
File_size_bytes : 0
Creation_datetime : 2015-11-03 6:54:02 PM
Last_update_datetime : 2015-11-03 6:54:02 PM
Last_read_datetime : 2015-11-03 6:54:02 PM
Folder_Name : C:\Temp
File_type : .log
File_name : Genre-List_2019-10-01.log
File_size_bytes : 178
Creation_datetime : 2019-10-01 12:33:47 PM
Last_update_datetime : 2019-10-01 12:33:47 PM
Last_read_datetime : 2019-10-01 12:33:47 PM