Обработка файлов .CSV в разных папках с помощью Powershell по-разному и экспорт в. html - PullRequest
0 голосов
/ 14 июля 2020

У меня есть куча файлов .csv, которые хранятся в разных папках, и я хочу разместить их как интерактивные кнопки в файле. html (разделенных именем папки).

В моем коде я добавил отдел IT, и он работает именно так, но неуместно обрабатывать каждый такой отдел, который у нас есть.

Я чувствую себя полностью потерянным и провел часы без какого-либо прогресса. У меня есть следующий код:

$out = 'C:\Project\test.html'
$it = "C:\Project\IT\"
$head = @"
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
"@
$Head | Out-File -filepath $out -Encoding utf8

#IT
$ITText = @"
<h3>IT</h3>
"@ 
$ITText | Out-File -FilePath $out -Encoding utf8 -Append
Get-ChildItem $it -Filter *.csv | ForEach-Object {
    $name = $_.BaseName
    $id = '{0}_{1}' -f $name, (Get-Date).Ticks  # to make this id unique, append the Ticks to the name    
    $Pre = @"
<p>
<button type="button" class="btn btn-Warning btn-sm" data-toggle="collapse" data-target="#$id">$name</button>
<div id="$id" class="collapse">
"@
    $Post = '</p></div>'
    Import-Csv -Path $_.FullName | ConvertTo-Html -Fragment -PreContent $pre -PostContent $post | 
    Out-File -FilePath $out -Encoding utf8 -Append
}

Это продолжение предыдущего вопроса

Спасибо!

1 Ответ

0 голосов
/ 14 июля 2020

Для этого вам нужно рекурсивно пройти путь $in и сгруппировать файлы CSV по имени их подпапки, которое, по-видимому, является именем отдела, которое вы хотите вывести как тег <h3>.

$in  = 'C:\Project'
$out = 'C:\Project\test.html'

$head = @'
<html>
  <head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
  </head>
<body>
'@
$Head | Out-File -filepath $out -Encoding utf8

$Pre = @'
<div class="container">
<h2></h2>
<button type="button" class="btn btn-info" data-toggle="collapse" data-target="#{0}">{1}</button>
<div id="{0}" class="collapse">
'@
$Post = '</p></div>'

Get-ChildItem $in -Filter *.csv -File -Recurse | 
    Group-Object {Split-Path $_.DirectoryName -Leaf} |   # group the files by the folder name and loop through
    ForEach-Object {
        # $_.Name is the name of the Group, aka the folder name aka the department name
        "<h3>$($_.Name)</h3>" | Out-File -FilePath $out -Encoding utf8 -Append
        # inside each department folder loop through the files
        foreach($file in $_.Group) {
            $name = $file.BaseName
            $id = '{0}_{1}' -f $name, (Get-Date).Ticks  # to make this id unique, append the Ticks to the name
            # use the $Pre template to fill in the placeholders
            $precontent = $Pre -f $id, $name
            Import-Csv -Path $file.FullName | ConvertTo-Html -Fragment -PreContent $precontent -PostContent $post | 
            Out-File -FilePath $out -Encoding utf8 -Append
        }
    }
# write html closing tags
'</body.</html>' | Out-File -FilePath $out -Encoding utf8 -Append

PS Вы забыли открывающие теги <html и <head>. Также не забудьте закрыть html, написав закрывающие теги </body></html>

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...