forked from dfinke/PowerShellNotebook
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathConvertToSQLNoteBook.ps1
More file actions
61 lines (53 loc) · 2.35 KB
/
Copy pathConvertToSQLNoteBook.ps1
File metadata and controls
61 lines (53 loc) · 2.35 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
function loadScriptDomModules{
Import-Module -Name SqlServer
$ScriptDom = Join-Path -Path (Get-Module -Name SqlServer).ModuleBase -ChildPath 'Microsoft.SqlServer.TransactSql.ScriptDom.dll'
if((Test-Path $ScriptDom) -eq $true ) {Add-Type -LiteralPath $ScriptDom}
}
# Quick Helper-function to turn the file into a script fragment, using scriptdom.
function Get-ScriptComments($ScriptPath){
[Microsoft.SqlServer.TransactSql.ScriptDom.TSql140Parser] $parser = new-object Microsoft.SqlServer.TransactSql.ScriptDom.TSql140Parser($false);
$Reader = New-Object -TypeName System.IO.StreamReader -ArgumentList $ScriptPath
$Errors = $null
$ScriptFrag = $parser.Parse($Reader, [ref]$Errors)
# Look for Drop Statements
($ScriptFrag.ScriptTokenStream).where({$_.TokenType -eq 'MultilineComment'})
}
function ConvertTo-SQLNoteBook {
<#
.Example
ConvertTo-PowerShellNoteBook -InputFileName c:\Temp\demo.txt -OutputNotebookName c:\Temp\demo.ipynb
#>
param(
$InputFileName,
$OutputNotebookName
)
loadScriptDomModules
New-SQLNotebook -NoteBookName $OutputNotebookName {
$s = Get-Content -Raw ( Resolve-Path $InputFileName )
$ScriptFrags = Get-ScriptComments -ScriptPath $InputFileName
$StartCode=0
foreach($Comment in $ScriptFrags ) {
$LengthCode = $Comment.Offset - $StartCode
$CodeBlock = $s.Substring($StartCode, $LengthCode)
Write-Verbose "CODE - $($CodeBlock)" -Verbose
if($CodeBlock.Trim().length -gt 0){
Add-NotebookCode -code (-join $CodeBlock)
}
$StartText= $Comment.Offset
$LengthText= $Comment.Text.Length
$TextBlock = $s.Substring($StartText+2, $LengthText-4) -replace ("\n", " `n ")
Write-Verbose "COMMENT - $($TextBlock)" -Verbose
if($TextBlock.Trim().length -gt 0){
Add-NotebookMarkdown -markdown (-join $TextBlock)
}
$StartCode= $StartText + $LengthText
}
# Left over code after last comment block
$LengthCode = $s.Length - $StartCode
$LastCodeBlock = $s.Substring($StartCode, $LengthCode)
Write-Verbose "CODE - $($LastCodeBlock)" -Verbose
if($LastCodeBlock.Trim().length -gt 0){
Add-NotebookCode -code (-join $LastCodeBlock)
}
}
}