2017-09-14 35 views
1

此刻我正在使用Powershell在SQL Server数据库上运行SQL查询并将结果输出到Excel电子表格中。在PowerShell输出文件中使用上个月的名称

目前,它通过

invoke-sqlcmd -inputfile "C:\scripts-and-reports\all_new-matters-since-last-run.sql" -serverinstance "PE-SERVER\PRACTICEEVOLVE" -database "PracticeEvolve_c1" | 
    Select-Object * -ExcludeProperty "RowError","RowState","Table","ItemArray","HasErrors" | 
    Export-XLSX -WorksheetName "15-05-2017 to $(get-date -f dd-MM-yyyy)" -Path "C:\scripts-and-reports\15-05-2017 to $(get-date -f yyyy-MM-dd) Taree PE new clients.xlsx" -Force -Verbose 

这是工作的罚款,因为我手动指定在SQL查询日期过滤器,在WorksheetName输出,并在文件名。

我的目标是使整个过程自动化,以便它在每个月的第一天运行并报告整个上个月。

我现在已经修改了我的SQL查询来筛选上个月,但是我希望输出文件的工作表和文件名只包含上个月的名称(例如,如果我正在运行“August”它今天)。

我已经试过

invoke-sqlcmd -inputfile "C:\scripts-and-reports\all_new-matters-for-last-month.sql" -serverinstance "PE-SERVER\PRACTICEEVOLVE" -database "PracticeEvolve_c1" | 
    Select-Object * -ExcludeProperty "RowError","RowState","Table","ItemArray","HasErrors" | 
    Export-XLSX -WorksheetName "$(get-date AddMonths(-1) -f MMMM)" -Path "C:\scripts-and-reports\$(get-date AddMonths(-1) -f MMMM) Taree PE new clients.xlsx" -Force -Verbose 

,但它不工作。我收到有关该字符串不是有效日期时间的错误。

我哪里错了,它应该是什么?

回答

6
get-date AddMonths(-1) -f MMMM 

此行是混合使用不同的语法,并且不适合在一起。

Get-Date is a cmdlet which takes a parameter -Format which can be shortened to -f 
Get-Date returns a [datetime] object 

.AddMonths() is a method on a [datetime] object, not a parameter to Get-Date 

更改为:

(Get-Date).AddMonths(-1).ToString('MMMM') 

它得到的日期,然后在此返回值调用AddMonths,然后使用该转换为文本的日期时间的方式,因为你不能使用-Format参数在这里,因为cmdlet调用较早完成。

+0

+1。我们可以在第二次调用'Get-Date'(即'(Get-Date).AddMonths(-1)| Get-Date -Format'MMMM'')时使用'-Format' ...但这并不完全简洁的调用'.ToString()'。 – BACON

+2

@BACON如果你想简洁..'日期|%* hs -1 |%* ost * MMMM';) – TessellatingHeckler

+0

感谢您的答复和解释。我是大多数脚本的业余爱好者,所以这非常有帮助! –

相关问题