为什么使用powershell将csv文件转换为excel时,得到空值expression式错误?

我有一个powershell脚本,从雅虎财经下载CSV文件,我的目标是将其转换为Excel文件(.xlsx)。 脚本是:

$path = "D:" $client = New-Object System.Net.WebClient $url = "http://download.finance.yahoo.com/d/quotes.csv?s=EDV,VEA,VWO,VHT,BND,VTI&f=sl1d1t1c1ohgv&e=.csv" $csv_filename = Join-Path $path "prices.csv" $client.DownloadFile($url, $csv_filename) $xl_filename = Join-Path $path "prices.xlsx" $xl = New-Object -COM "Excel.Application" $xl.Visible = $true $wb = $xl.Workbooks.OpenText($csv_filename) $wb.SaveAs($xl_filename, 51) $wb.Close() $xl.Quit() [System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl) 

该脚本位于`D:\ get_prices.ps1',我执行它

C:\ Windows \ System32 \ WindowsPowerShell \ v1.0 \ powershell.exe -ExecutionPolicy Unrestricted -File D:\ get_prices.ps1

当我运行它时,我得到两个错误:

 You cannot call a method on a null-valued expression. At D:\get_prices.ps1:14 char:11 + $wb.SaveAs <<<< ($xl_filename, 51) + CategoryInfo : InvalidOperation: (SaveAs:String) [], RuntimeExc eption + FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At D:\get_prices.ps1:15 char:10 + $wb.Close <<<< () + CategoryInfo : InvalidOperation: (Close:String) [], RuntimeExce ption + FullyQualifiedErrorId : InvokeMethodOnNull 

转换代码是从这个问题的答案( 如何使用Powershell将CSV导出到Excel )进行调整的。

我查看了Workbook.SaveAs的文档,只要我正确地使用它,文件格式( 51参数)也是正确的。 我也看了Workbook.Close的文档,看起来也是正确的。

我在Windows 7 x64上使用powershell v2.0(根据get-host )和Excel 2013。

我究竟做错了什么?

$xl.Workbooks.OpenText返回void不是工作簿。

做这个改变:

 $xl.Workbooks.OpenText($csv_filename) $wb=$xl.ActiveWorkbook