forked from dfinke/PowerShellNotebook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInvokePowerShellNotebook.ps1
54 lines (46 loc) · 1.88 KB
/
InvokePowerShellNotebook.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
function Invoke-PowerShellNotebook {
param(
[Parameter(ValueFromPipelineByPropertyName)]
$NoteBookFullName,
[Switch]$AsExcel,
[Switch]$Show
)
Process {
$codeBlocks = Get-NotebookContent $NoteBookFullName -JustCode
$codeBlockCount = $codeBlocks.Count
$SheetCount = 0
for ($idx = 0; $idx -lt $codeBlockCount; $idx++) {
$targetCode = $codeblocks[$idx].source
Write-Progress -Activity "Executing PowerShell code block - [$(Get-Date)]" -Status (-join $targetCode) -PercentComplete (($idx + 1) / $codeBlockCount * 100)
if ($AsExcel) {
if (!(Get-Module -ListAvailable ImportExcel -ErrorAction SilentlyContinue)) {
throw "This feature requires the ImportExcel PowerShell module. Use 'Install-Module -Name ImportExcel' to get it from the PS Gallery."
}
if ($idx -eq 0) {
$notebookFileName = Split-Path $NoteBookFullName -Leaf
$xlFileName = $notebookFileName -replace ".ipynb", ".xlsx"
$xlfile = "{0}\{1}" -f $pwd.Path, $xlFileName
Remove-Item $xlfile -ErrorAction SilentlyContinue
}
foreach ($dataSet in , @($targetCode | Invoke-Expression)) {
if ($dataSet) {
$SheetCount++
$uniqueName = "Sheet$($SheetCount)"
Export-Excel -InputObject $dataSet -Path $xlfile -WorksheetName $uniqueName -AutoSize -TableName $uniqueName
}
}
}
else {
, @($targetCode | Invoke-Expression)
}
}
if ($AsExcel) {
if ($Show) {
Invoke-Item $xlfile
}
else {
$xlfile
}
}
}
}