脚本中的Power shell自定义功能

时间:2017-07-17 13:36:07

标签: sql-server excel powershell csv

我准备了一个脚本来提取一些报告w.r.t SQL server和out put将被推送到不同的CSV表。生成输出后,借助自定义创建的功能将所有CSV合并为单个Excel文件,并将excel发送到我的电子邮件地址。

运行htrough powershell_ise.exe时,它运行正常,我收到了成功的电子邮件。当我安排相同的脚本时,我收到的是电子邮件,但没有excel附件。我怀疑没有使用自定义创建的功能,因为我没有在所需的位置看到任何转换的excel文件。

我尝试了所有可能的方法,比如点乱码,在脚本本身粘贴功能但没有运气。

我是powershell的初学者,如果我遗漏某些东西,请帮助我。

谢谢, 阿尼尔

Function Merge-CSVFiles
{
Param(
$CSVPath = "D:\Anil\Missing_Indexes", ## Soruce CSV Folder
$XLOutput="D:\Anil\Missing_Indexes.xls" ## Output file name
)

$csvFiles = Get-ChildItem ("$CSVPath\*") -Include *.csv
$Excel = New-Object -ComObject excel.application 
$Excel.visible = $false
$Excel.sheetsInNewWorkbook = $csvFiles.Count
$workbooks = $excel.Workbooks.Add()
$CSVSheet = 1

Foreach ($CSV in $Csvfiles)

{
$worksheets = $workbooks.worksheets
$CSVFullPath = $CSV.FullName
$SheetName = ($CSV.name -split "\.")[0]
$worksheet = $worksheets.Item($CSVSheet)
$worksheet.Name = $SheetName
$TxtConnector = ("TEXT;" + $CSVFullPath)
$CellRef = $worksheet.Range("A1")
$Connector = $worksheet.QueryTables.add($TxtConnector,$CellRef)
$worksheet.QueryTables.item($Connector.name).TextFileCommaDelimiter = $True
$worksheet.QueryTables.item($Connector.name).TextFileParseType  = 1
$worksheet.QueryTables.item($Connector.name).Refresh()
$worksheet.QueryTables.item($Connector.name).delete()
$worksheet.UsedRange.EntireColumn.AutoFit()
$CSVSheet++

}

$workbooks.SaveAs($XLOutput,51)
$workbooks.Saved = $true
$workbooks.Close()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbooks) | Out-Null
$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

}

1 个答案:

答案 0 :(得分:0)

  

在运行powershell_ise.exe时,运行正常,我收到了成功的电子邮件

这是因为您的盒子上的ISE能够在运行时加载您的自定义函数并生成报告。

但是当通过作业安排此操作时,脚本将在与您的盒子不同的服务器上运行,因此脚本将无法找到该功能而您也无法获得该报告。

我在使用自定义函数之前遇到过这种问题。

我可以建议的解决方法是将自定义函数包装在单独的模块中,然后在主脚本中导入模块。 (最好将模块保存在与脚本相同的位置,以便于故障排除)。

实施例: 将您的功能保存在.psm1模块文件中

Function ScriptExample {
Param ( [string] $script,
        [string] $jobname,
        [string] $jobcategory,
        [hashtable] $config,
        [string] $deletelogfilepath,
        [string] $servername)



#your-function-here#
 {
    }

Return $script;

}

现在在主脚本中调用此模块,如下所示,

$importmoduleroot = "C:\temp\SO_Example.psm1"

###### LOAD MODULES ######

# Import all related modules written to support this process
$modules = get-childitem -path $importmoduleroot -include SO*.psm1 -recurse;

然后,您可以调用您的函数并传入主脚本中的参数

ScriptExample -script $script `
            -jobname $jobname `
            -jobcategory $jobcategory `
            -config $config `
            -servername $ServerName `
            -deletelogfilepath $deletelogfilepath