作为一些背景,这应该是一个excel文件,并将其转换为PDF (并将PDF放入一个临时文件夹)。
例如。'C:\Users\gjacobs\Desktop\test\stock.xlsx‘变成C:\Users\gjacobs\Desktop\test\stock.xlsx
但是,新的文件路径不能正确返回。
如果我从函数中回显字符串"C:\Users\gjacobs\Desktop\test\pdf_merge_tmp\stock.pdf".,我可以看到它具有正确的值:$export_name
但是一旦返回了C:\Users\gjacobs\Desktop\test\pdf_merge_tmp\stock.pdf".,它就会有一个不同的值(不正确的值):"C:\Users\gjacobs\Desktop\test\pdf_merge_tmp $export_name
function excel_topdf{
param(
$file
)
#Get the parent path
$parent = Split-Path -Path $file
#Get the filename (no ext)
$leaf = (Get-Item $file).Basename
#Add them together.
$export_name = $parent + "\pdf_merge_tmp\" + $leaf + ".pdf"
echo ($export_name) #prints without issue.
#Create tmp dir
New-Item -Path $parent -Name "pdf_merge_tmp" -ItemType "Directory" -Force
$objExcel = New-Object -ComObject excel.application
$objExcel.visible = $false
$workbook = $objExcel.workbooks.open($file, 3)
$workbook.Saved = $true
$xlFixedFormat = “Microsoft.Office.Interop.Excel.xlFixedFormatType” -as [type]
$workbook.ExportAsFixedFormat($xlFixedFormat::xlTypePDF, $export_name)
$objExcel.Workbooks.close()
$objExcel.Quit()
return $export_name
}
$a = excel_topdf -file 'C:\Users\gjacobs\Desktop\test\stock.xlsx'
echo ($a)发布于 2021-01-12 14:23:31
您正在经历的问题是由PowerShell从函数返回的方式引起的。它并不局限于New-Item cmdlet。每个返回任何内容的cmdlet都会导致函数输出与该cmdlet的值发生更改。
例如,让我们使用一个cmdlet函数,它返回一个对象:
function a {
Get-Item -Path .
}
$outputA = a
$outputA
#### RESULT ####
Directory:
Mode LastWriteTime Length Name
---- ------------- ------ ----
d--hs- 12/01/2021 10:47 C:\如果您想避免这种情况,这些是最流行的选项(正如Lasse V. Karlsen在评论中指出的那样):
# Assignment to $null (or any other variable)
$null = Get-Item -Path .
# Piping to Out-Null
Get-Item -Path . | Out-Null注意事项:上述行为不适用于Write-Host
function b {
Write-Host "bbbbbb"
}
$outputB = b
$outputB
# Nothing displayedhttps://stackoverflow.com/questions/65684452
复制相似问题