Is there a way to pull a variable value into a select-object expression?

272 views Asked by At

The purpose of this script is to find the Name, directory and last write time of files and output it to a csv file.

get-childitem D:\testing -recurse -filter *.txt | select-object Name,DirectoryName,LastWriteTime, @{Name="New_colimn";Expression={"copy-item \`"DirectoryName\`" To_Compile_directory"}} | where { $_.DirectoryName -ne $NULL } | Export-CSV D:\testing\rdf.csv

My problem is that there is 1 cell I want to fill with another script that takes values from the generated csv file. Is there a way to pull the value of each DirectoryName and paste it into the Expression of the same row? I only get an error that says DirectoryName is an invalid key.

when I try to pull using $.DirectoryName the script only reads the $ and the value it has is the Name.

Thank for helping.

1

There are 1 answers

3
Theo On BEST ANSWER

Did you mean to collect the data from the files like this:

Get-ChildItem -Path 'D:\testing' -Filter '*.txt' -File -Recurse | 
Select-Object Name,DirectoryName,LastWriteTime | Export-Csv -Path 'D:\testing\rdf.csv' -NoTypeInformation

and then have your other script read the DirectoryName's from it like this?

$directories = (Import-Csv -Path 'D:\testing\rdf.csv').DirectoryName | Select-Object -Unique
# maybe do something with these directories here?
foreach ($folderPath in $directories) {
    # copy the directories including the files to an existing root destination folder
    Copy-Item -Path $folderPath -Destination 'D:\SomeExistingDestinationPath' -Recurse -Force
}