Basically, I have a CSV file that lists the content of a directory to analyze for any missing files.
My script does this, however I am trying to export the results of the missing files to a new CSV file.
Current script:
#get working directory
$documents = 'C:\Users\Me\Documents\ScriptTest'
#path to files located in the directory
$myFolder = Get-ChildItem 'C:\Users\Me\Documents\Test\1' -Recurse -Include *.txt |
Select-Object -ExpandProperty BaseName |
Where-Object{$_ -notmatch "\\FolderName\\"}
#get items located in CSV file list column
$myCSV = Import-CSV -Path 'C:\Users\Me\Documents\Test.csv' |
Select-Object -ExpandProperty 'File Path'
$CSVexport = '\Users\Me\Documents\Test.csv'
$results=@()
$desiredColumns = @{
ID = $CSVexport | Select-Object ID
'File Path' = $CSVexport | Select-Object 'File Path'
}
#split the CSV item names
$splits=@()
foreach($file in $myCSV){
$split = $file.split("\\")[2]
$split2 = $split.split(".")[0]
$splits+=$split2
}
#compare the CSV items to the folder items
$compare = Compare-Object -ReferenceObject $splits -DifferenceObject $myFolder -includeequal
Write-Output "`n_____Results____`n"
#Write the results and export to a CSV file
$compare | ForEach-Object {
if($_.SideIndicator -eq "<="){
write-host "`n$($_.InputObject) is missing from the Test folder.`n"
$results = New-Object PSObject -Property $desiredColumns
$results.'File Path' = $_.InputObject
$results | Export-Csv -Path C:\Users\Me\Documents\Results.csv –NoTypeInformation
}
}
All I get back is:
It only gets one of the missing files and nothing for the "ID" column. I want to be able to get the result of the comparison and export it to a new CSV with the related columns from the first CSV file. For example:
Can I get some help as to what I might be doing wrong?
New Code:
$documents = 'C:\Users\Me\Documents'
$NewCsv = Import-CSV -Path 'C:\Users\Me\Documents\Test.csv' |
Select-Object ID,'File Path' |
ForEach-Object {
if (!(Test-Path (Join-Path $documents $_.'File Path'))){
[PSCustomObject]@{
ID = $_.ID
Missing = $_.'File Path'
}
}
}
$NewCsv
Output:
Name Value
---- -----
ID 4
Missing Test\1\File4.txt
ID 6
Missing Test\1\File6.txt
Extremely over complicated.
If you iterate your csv, check the existence of every file and generate a new csv on the fly, it can be as simple as:
## Q:\Test\2018\05\24\SO_50517360.ps1
$BasePath = "C:\Users\Me\Documents"
$NewCsv = Import-CSV -Path '.\Test.csv'|Select-Object ID,'File Path' |
ForEach-Object {
if (!(Test-Path (Join-Path $BasePath $_.'File Path'))){
[PSCustomObject]@{
ID = $_.ID
Missing = $_.'File Path'
}
}
}
$NewCsv
Sample output (which can be put in a new file by
$NewCsv|Export-Csv .\Missing.csv -NoTypeInformation
> .\SO_50517360.ps1
ID Missing
-- -------
4 Test\1\File4.txt
6 Test\1\File6.txt