Результат экспорта Powershell в файл xlsx - PullRequest
0 голосов
/ 07 апреля 2020

Если я хочу изменить формат файла экспорта на excel, есть ли способ сделать это?

Спасибо.

Сценарий Powershell

Import-Module ActiveDirectory

$refDate = (Get-Date).AddDays(1).Date
New-PSDrive -Name UNCPath -PSProvider FileSystem -Root "\\Test-PC\Test\"
$logTime = Get-Date -Format "yyyyMMdd"
$logFile = 'UNCPath:\Log\'+$logTime+".log"

start-transcript $logFile

$users = Get-AdUser -Filter {AccountExpirationDate -eq $refDate} –Properties EmailAddress, AccountExpirationDate -ErrorAction SilentlyContinue
if ($users) {
      $fileOut = 'UNCPath:\'+ 'ExpiryUserList' + ".csv"
    $users | Select-Object -Property SamAccountName, Name, EmailAddress, AccountExpirationDate | 
    Export-CSV -Path $fileOut -NoTypeInformation
    Write-Host ""
    Write-Host "Result: Record have found!"
    Write-Host ""
    Stop-Transcript
}
else {     
   Write-Host ""
   Write-Host "Result: No expired accounts found!"
   Write-Host ""
   Stop-Transcript
}

1 Ответ

0 голосов
/ 07 апреля 2020

Excel будет читать csv с нуля, как мы все знаем, но чтобы узнать, что вам нужно, вам нужно преобразовать этот CSv в XL *.

Так что рефакторинг вашего кода немного ...

Import-Module ActiveDirectory

$refDate = (Get-Date).AddDays(1).Date

# Note, you are nto using this anywhere in your code, so why specify this at all
# New-PSDrive -Name UNCPath -PSProvider FileSystem -Root "\\Test-PC\Test\"

$logTime = Get-Date -Format "yyyyMMdd"
$logFile = "UNCPath:\Log\$($logTime).log"

start-transcript $logFile

$users = Get-AdUser -Filter {AccountExpirationDate -eq $refDate} –Properties EmailAddress, AccountExpirationDate -ErrorAction SilentlyContinue
if ($users) 
{
    $fileOut = 'UNCPath:\ExpiryUserList.csv'

    $users | Select-Object -Property SamAccountName, Name, EmailAddress, AccountExpirationDate | 
    Export-Csv -UseCulture -Path $fileOut -NoTypeInformation -Encoding UTF8

     "`nResult: Record have found!`n"

    # Convert to Excel format by a load into Excel
    $excel = New-Object -ComObject Excel.Application 
    $excel.Visible = $true
    $excel.Workbooks.Open("$fileOut").SaveAs("$($fileOut.BaseName).xlsx",51)
    $excel.Quit()

    explorer.exe "/Select,$fileOut"
}
else {Write-Warning -Message "`nResult: No expired accounts found!`n"}

Stop-Transcript

Но, я согласен с AdminOfThings, есть модули через MS powershellgallery.com, которые могут быть более разумными для использования.

Find-Module -Name '*Excel*' | Format-Table -AutoSize

<#
# Results

Version     Name                          Repository Description
-------     ----                          ---------- -----------
7.1.0       ImportExcel                   PSGallery  PowerShell module to import/export Excel spreadsheets, without Excel....
0.1.5       PSWriteExcel                  PSGallery  Little project to create Excel files without Microsoft Excel being installed.
1.0.2       PSExcel                       PSGallery  Work with Excel without installing Excel
19.0.7354.0 ExcelCmdlets                  PSGallery  CData Cmdlets for Excel
19.0.7354.0 ExcelServicesCmdlets          PSGallery  CData Cmdlets for Excel Services
0.1.6       BitTitan.Runbooks.Excel       PSGallery  PowerShell module for Excel-related functions and resources used in BitTitan Runbooks
19.0.7354.0 ExcelOnlineCmdlets            PSGallery  CData Cmdlets for Excel Online
0.6.9       ExcelPSLib                    PSGallery  Allow simple creation and manipulation of XLSX file
0.1.6       BitTitan.Runbooks.Excel.Beta  PSGallery  PowerShell module for Excel-related functions and resources used in BitTitan Runbooks
0.0.4       Excelimo                      PSGallery  Simple project generating Excel Workbooks/Worksheets
0.0.1       ProductivityTools.PSExcel2SQL PSGallery  Module takes all excel files in given directory and push the content to database.
#>
...