复制到剪贴板 Powershell 故障

Copy to Clipboard Powershell Glitch

我用 Powershell 创建了脚本,将数据表的结果复制到剪贴板,以便将其粘贴到 Excel:

        $excelArray = New-Object 'object[,]' $dt_table1.Rows.Count, $dt_table1.Columns.Count
        $excelArray = ForEach($Row in $dt1.Tables[0].Rows)
                        {
                            $Record = New-Object PSObject
                            ForEach($Col in $dt1.Tables[0].Columns.ColumnName)
                            {
                                Add-Member -InputObject $Record -NotePropertyName $Col -NotePropertyValue $Row.$Col
                            }
                            $Record
                        }
        $excelArray | ConvertTo-CSV -NoType -Del "`t" | Select -Skip 1 | Clip
        [void]$WorkSheet.columns.Item(1).cells.Item(2).PasteSpecial()
        $WorkSheet.Visible = $false

当我使用“Powershell ISE”执行脚本时,脚本工作正常,当我使用“Windows 任务计划程序”中的 CMD 批处理计划此脚本时,问题就来了。当管理员用户连接到 RDP 并且通过调度程序执行此批处理时,它不会将结果复制到 excel sheet,它会复制我在剪贴板中的最后一个东西。

当执行批处理并关闭 RDP 会话时,批处理失败但没有给我任何错误.....这是怎么回事?也许还有另一种方法可以将数据表或数据集的结果复制到 xcel sheet 以避免剪贴板?

谢谢!

使用 Excel 文件的更好方法是使用模块 ImportExcel。它使用 EPPLUS 库,因此您不必使用任何 COM 对象,在服务器上安装 Excel 或使用剪贴板。

将数据导出到 Excel 文件的一种方法是简单地使用 Export-Excel.

首先您需要从 PowerShell Gallery 安装模块:

Install-Module ImportExcel

然后你就可以在你的脚本中使用它了:

# myScript.ps1
#Requires -Module ImportExcel

Param (
    $Path = 'C:\path\to\the.xlsx'
)

$exportToExcel = ForEach ($Row in $dt1.Tables[0].Rows) {
    $properties = @{}
    ForEach ($Col in $dt1.Tables[0].Columns.ColumnName) {
        $properties[$Col] = $Row.$Col 
    }
    [PSCustomObject]$properties
}

$params = @{
    Path          = $Path 
    WorksheetName = 'Data' 
    TableName     = 'Data'
    FreezeTopRow  = $true
    # HideSheet     = 'Data' 
}
$exportToExcel | Export-Excel @params

一些有助于您入门的命令:

Get-Help Export-Excel # displays what a function, its parameters, ..
Get-Help Export-Excel -Examples # displays how to use the function
Get-Command -Module ImportExcel # list all available functions in a module