【问题标题】:Powershell Excel Automation Save Workbook by DatePowershell Excel 自动化按日期保存工作簿
【发布时间】:2012-09-05 00:14:54
【问题描述】:

我正在创建一个 powershell 脚本,以使用 SCVMM 中的“get-vm”命令中的信息填充 excel 工作簿。

保存文件路径目前正在进行中。 我想每天或每周运行脚本,并使用该日期作为文件名保存生成的 Excel 工作簿。这可能吗?如何生成日期并将其用作保存 excel 输出的文件名?任何帮助都会很棒。

#run below line once and then comment out if not in VMM Command Shell. Will import modules for ISE/Powershell.
#Import-Module "C:\Program Files\Microsoft System Center 2012\Virtual Machine Manager\bin\psModules\virtualmachinemanager\virtualmachinemanager"

$server = Get-VMMServer -ComputerName "server"

$vminfo = Get-VM -VMMServer $server 

$xl=New-Object -ComObject "Excel.Application"
$wb=$xl.Workbooks.Add()
$ws=$wb.ActiveSheet
$cells=$ws.Cells
$xl.Visible=$True

$cells.item(1,1)="{0} VMM Server Report" -f $server.Name
$cells.item(1,1).font.bold=$True
$cells.item(1,1).font.size=18

#define some variables to control navigation
$row=3
$col=1

#insert column headings
"Name", "Description", "OperatingSystem", "CPUCount","Memory (GB)", "Status", "Hostname" | foreach {
$cells.item($row,$col)=$_
$cells.item($row,$col).font.bold=$True
$col++
}

foreach ($vm in $vminfo) {
$row++
$col=1
$cells.item($row,$col)=$vm.Name
$col++
$cells.item($row,$col)=$vm.Description
$col++
$cells.item($row,$col)=$vm.OperatingSystem.Name
$col++
$cells.item($row,$col)=$vm.CPUCount
$col++
$cells.item($row,$col)=$vm.Memory/1024
$col++
$cells.item($row,$col)=$vm.Status
$col++
$cells.item($row,$col)=$vm.HostName
}
$objRange = $ws.UsedRange 
$objRange.EntireColumn.Autofit() 

$date = get-date -DisplayHint date 

$filepath="C:\Users\paulm\Documents\"

if ($filepath) {
$wb.SaveAs($filepath)

}

完成的保存脚本如下所示:

$date = Get-Date -Format yyyy-MM-dd 

$wb.SaveAs("C:\Users\paulm\Documents\$date")+ ".xls"

【问题讨论】:

    标签: excel date powershell save


    【解决方案1】:

    函数是Get-Date。不带参数调用它将返回当前日期。像这样的

    (Get-Date -Format yyyy-MM-dd) + ".xls"
    

    会给你一个可用的文件名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多