I wish to send file and folder attributes to either a csv file or to the screen depending on the boolean value of $debug. I have tried to accomplish this by including a ternary operator in the end of the following pipeline:
Get-ChildItem $directory -Recurse -File |
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)}} |
(&{if ($debug) {Write-Host} else {Export-Csv -path $outpath -NoTypeInformation -force -Delimiter ';'}})
Is this a bad approach, and which approach is recommended?
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-Objectcall with anifto test the output destination. it also adds an-ErrorActionto theGet-ChildItemcall to handle "inaccessible file" errors.it also removes the unneeded
$()in theexpression =lines.1st three lines of the CSV ...
the 1st three items of the screen output ...