This is a very simple script that we needed for cleaning up file systems where junk had been left behind. It's not complicated. It just checks to see if the file in question is part of a database on the server. If not, it removes it.

Regarding the script itself, it's using foreach rather than the pipe because I was having trouble getting the pipe to work. I'm still working on the script and may update it when I get the other approach to work correctly.

PowerShell
Edit|Remove
param([string]$filelocation="",[string]$sqlinstance="(local)")

Set-Location $filelocation 
foreach($file in get-childitem)
{$base = $file.Name;
$result = Invoke-Sqlcmd -ServerInstance $sqlinstance -Query "SELECT DB_NAME(mf.database_id) AS db FROM sys.master_files mf WHERE RIGHT(mf.physical_name,LEN('$Base')) = '$Base' UNION ALL SELECT 'NoDb' AS db WHERE NOT EXISTS (SELECT DB_NAME(mf.database_id) AS db FROM sys.master_files mf WHERE RIGHT(mf.physical_name,LEN('$Base')) = '$Base');" ;  
if($result.DB -eq "NoDb" -and $file.Extension -ne ".cer"){Remove-Item $base}}