【问题标题】:powershell not exportingpowershell不导出
【发布时间】:2021-10-10 13:12:35
【问题描述】:

您好,我正在 powershell 中运行以下查询:

Import-Module Hall.psm1

$Database = 'Report'
$Server = '192.168.1.2'
$Query = 'SELECT all * FROM [Report].[dbo].[TestView]'
$LogLocation = "\\Report\LogFile.csv"
$DynamicYear = (Get-Date).Year
$DynamicMonth = (Get-Culture).DateTimeFormat.GetMonthName((Get-Date).Month)
$FileDestination = "\\Report\MONTHLY REPORTS\"+$DynamicYear+"\"+$DynamicMonth+"\"
$Outputfilename='TestView-'+(Get-Date).ToString('MM-dd-yyyy')+'.csv'
$LocalCreate = 'C:\Scripts\LocalCreate\'
$FolderPathExtension = "Microsoft.PowerShell.Core\FileSystem::"
$CodeDestination = $FolderPathExtension+$FileDestination
$filedest=$LocalCreate+$outputfilename
$Logfile = $FolderPathExtension+$LogLocation

Invoke-sqlcmd -querytimeout 120 -query "
$Query
" -database $database -serverinstance $server |

ConvertTo-Csv -NoTypeInformation | # Convert to CSV string data without the type metadata
Select-Object -Skip 0 | # Trim header row, leaving only data columns
% {$_ -replace '"',''} | # Remove all quote marks

Set-Content -Path $filedest

(gc $filedest) | ? {$_.trim() -ne "" } | set-content $filedest

if(Test-Path ($filedest)) { 
Move-Item -Path $filedest -Destination $CodeDestination -Force

$LogType = 'INFO'
$LogEntry = "$filedest MovedTo $To"
Write-Log -Message $LogEntry -Level $LogType -Logfile $Logfile
}

如果查询有数据,它可以正常工作,没有任何问题。 但是,如果查询没有任何数据,则不会创建 .csv。我怎样才能让它创建一个空白的.csv?还是仅带有标题的 .csv?

【问题讨论】:

  • 先创建一个空白文件,这样不管你有没有内容要写入它都会存在

标签: sql powershell csv


【解决方案1】:

Invoke-SqlCmdConvertTo-Csv 之前使用 New-Item -ItemType File -Path $filedest

【讨论】:

    猜你喜欢
    • 2023-03-15
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多