forked from dfinke/PowerShellNotebook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInvokeExecuteNotebook.ps1
More file actions
107 lines (84 loc) · 2.88 KB
/
Copy pathInvokeExecuteNotebook.ps1
File metadata and controls
107 lines (84 loc) · 2.88 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
function Find-ParameterizedCell {
<#
.Synopsis
Reads a Jupyter Notebook and returns all cells with a tag -eq to 'parameters'
#>
param(
[Parameter(Mandatory)]
$InputNotebook
)
$data = ConvertFrom-Json -InputObject (Get-Content -Raw $InputNotebook)
for ($idx = 0; $idx -lt $data.cells.Count; $idx++) {
$currentCell = $data.cells[$idx]
if ($currentCell.metadata.tags -eq 'parameters') {
$idx
}
}
}
function Get-ParameterInsertionIndex {
param(
[Parameter(Mandatory)]
$InputNotebook
)
$cell = Find-ParameterizedCell $InputNotebook | Select-Object -First 1
if ([string]::IsNullOrEmpty($cell)) {
return 0
}
$cell + 1
}
function Invoke-ExecuteNotebook {
param(
$InputNotebook,
$OutputNotebook,
[hashtable]$Parameters
)
if (!$InputNotebook) { return }
$data = Get-Content $inputNotebook | ConvertFrom-Json
[System.Collections.ArrayList]$cells = $data.cells
$PSNotebookRunspace = New-PSNotebookRunspace
if ($Parameters) {
$newVars = @("# override parameters")
$newVars += $(
foreach ($entry in $parameters.GetEnumerator() ) {
$quote = $null
$currentValue = $entry.value
if ($currentValue -is [string]) { $quote = "'" }
'${0} = {1}{2}{1}' -f $entry.name, $quote, $currentValue
# "`$$($entry.name) = $($entry.value)"
}
)
$newParams = New-CodeCell ($newVars -join "`r`n") | ConvertFrom-Json
$index = Get-ParameterInsertionIndex -InputNotebook $InputNotebook
$cells.Insert($index, $newParams)
}
for ($idx = 0; $idx -lt $cells.count; $idx++) {
$PSNotebookRunspace.PowerShell.Commands.Clear()
$cell = $cells[$idx]
$result = $PSNotebookRunspace.Invoke($cell.source)
if ($cell.outputs -and $cell.outputs.text) {
$cell.outputs[0].text = $result
}
}
$data.cells = $cells
if ($OutputNotebook) {
if ($outputNotebook.startswith("gist://")) {
$OutFile = $OutputNotebook.replace("gist://", "")
$targetFileName = Split-Path $OutFile -Leaf
$contents = $data | ConvertTo-Json -Depth 4
$result = New-GistNotebook -contents $contents -fileName $targetFileName
if ($result) {
Start-Process $result.html_url
}
}
else {
if (Test-Path $OutputNotebook) {
throw "$OutputNotebook already exists"
}
ConvertTo-Json -InputObject $data -Depth 4 |
Set-Content $OutputNotebook -Encoding utf8
}
}
else {
$data.cells.outputs.text
}
}