I have a table that contains information pointing to files stored on a file server. I’m trying to write a powershell script to verify that each record in the table has a physical file associated with it on the server, if it does not write to the CSV file. I’m not having much luck wit the csv portion and was hoping you could help?
Here is what I have so far (please let me know if there are better ways to do this, Im brand new to powershell). I only want to add records to the csv if the test-path fails to find the file in question.
[Reflection.Assembly]::LoadFile("C:\ora10g\odp.net\bin\2.x\Oracle.DataAccess.dll")
$connectionString = "Data Source=XXXXXX;User Id=XXXX;Password=XXXXXXXX;"
$connection = New-Object Oracle.DataAccess.Client.OracleConnection($connectionString)
$connection.Open()
$queryString = "SELECT Key, Sequence, Type, File FROM FileTable WHERE Type IN (2, 5)"
$command = new-Object Oracle.DataAccess.Client.OracleCommand($queryString, $connection)
$mediaObjRS = $command.ExecuteReader()
# Loop through recordset
while ($mediaObjRS.read()) {
# Assign variables from recordset.
$objectKey = $mediaObjRS.GetString(0)
$objectSeq = $mediaObjRS.GetDecimal(1)
$objectType = $mediaObjRS.GetDecimal(2)
$objectFileName = $mediaObjRS.GetString(3)
# Check if file exists based on filetype.
if($objectType -eq 2){
# Type 2 = OLE
$fileLocation = "\\fileserver\D$\files\" + $objectFileName
}elseif($objectType -eq 5){
# Type 5 = FILE
$fileLocation = $objectFileName
}
$fileExists = Test-Path $fileLocation
if($fileExists -eq $False){
#Write to output file
$objectKey | Export-Csv missingfiles.csv
$objectSeq | Export-Csv missingfiles.csv
$objectType | Export-Csv missingfiles.csv
$objectFileName | Export-Csv missingfiles.csv
}
}
$connection.Close()
Each time you write to the missingfiles.cs you clobber the previous one. Plus this cmdlet is oriented towards saving objects where each property represents one of the comma separated values.
The simplest way to do this is to manually write (append) to the csv file:
The “slick” PowerShell way to do it would be to create an object for each file and then put those in an array and when you’re done, export that array of object to a CSV file e.g.: