Remove last Line from a File Powershell


Since version 5, we can use Select skiplast . for earlier versions, we can use search or array count to skip the last row.


$q = @"

SELECT  [CustomerID],[CompanyName]
  FROM [Northwind].[dbo].[Customers]
 where CustomerID='XXXXXX'
 UNION ALL
Select '' CustomerID, ''CompanyName

"@
Invoke-SQLCmd -ServerInstance $svr.Name  -Database $db -Query $q |  Export-Csv -NoTypeInformation -delimiter "`t" -Path $myPath0
gc $myPath0 | % {$_ -replace '"', ""} | Select -SkipLast 1 | out-file $myPath -Fo -En ascii


Use -notlike:

 
 $q = @" SELECT  [CustomerID],[CompanyName] FROM [Northwind].[dbo].[Customers] where CustomerID='XXXXXX' UNION ALL Select 'dummy' CustomerID, ''CompanyName "@ Invoke-SQLCmd -ServerInstance $svr.Name  -Database $db -Query $q |  Export-Csv -NoTypeInformation -delimiter "`t" -Path $myPath0 gc $myPath0 | % {$_ -replace '"', ""} | Where-Object {$_ -notlike "*dummy*"}| out-file $myPath -Fo -En ascii

–Or use array count:

 
 $q = @" SELECT [CustomerID],[CompanyName] FROM [Northwind].[dbo].[Customers] where CustomerID='XXXXXX' UNION ALL Select 'dummy' CustomerID, ''CompanyName "@ Invoke-SQLCmd -ServerInstance $svr.Name -Database $db -Query $q | Export-Csv -NoTypeInformation -delimiter "`t" -Path $myPath0 $file=gc $myPath0 $file[0..(($file).count - 2)] | % {$_ -replace '"', ""} | out-file $myPath -Fo -En ascii

https://www.poshcodebear.com/blog/2014/2/1/removing-the-first-or-last-lines-from-a-text-file

https://social.msdn.microsoft.com/Forums/sqlserver/en-US/06598ae8-cfc1-4c82-9718-88fd47f91f8b/powershell-converttocsv-how-do-you-print-headers-only-when-no-results-returned-from?forum=transactsql

Advertisements


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s