I have a strange error occurring when using the invoke-sqlcmd to insert rows into a table. The entire script works perfectly if executed one time, but if I run it a second time,
The answers posted helped me to understand the problem but were not specific enough to provide a solution that worked in my environment. This is what solved the problem for me:
$latestFile = Get-ChildItem Microsoft.PowerShell.Core\FileSystem::$dir | where-Object {$_.Name.ToString() -like $databasePattern} | Sort-Object LastAccessTime -Descending | Select-Object -First 1
The ToString() was required for success. The complete problem statement, debugging, and solution were posted at https://social.msdn.microsoft.com/Forums/sqlserver/en-US/f28d9276-7aad-464c-823e-b9b4637856e1/powershell-script-using-getchilditem-works-with-invokesqlcmd-when-called-from-visual-studio-code?forum=sqlkjmanageability&prof=required I provided the link only for research and attribution purposes. In accordance with StackOverflow's convention of wanting complete solutions instead of links, what I posted was the complete solution to the problem as manifested in my environment.