-
Notifications
You must be signed in to change notification settings - Fork 14
/
ConvertTo-ModuleService.ps1
10234 lines (8011 loc) · 860 KB
/
ConvertTo-ModuleService.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
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function ConvertTo-ModuleService
{
<#
.Synopsis
Export a PowerShell module as a series of ASP.NET Handlers
.Description
Exports a Powershell module as a series of ASP.NET handlers
.Example
Import-Module Pipeworks -Force -PassThru | ConvertTo-ModuleService -Force -Allowdownload
.Link
Invoke-WebCommand
#>
[OutputType([Nullable])]
param(
#|Options Get-Module | Select-Object -ExpandProperty Name
# The name of the module to export
[ValidateScript({
if (-not (Get-Module "$_")) {
$isavailable = Get-Module -ListAvailable "$_"
if ($isavailable) {
$isavailable | Import-Module -Global
}
}
return $true
})]
[Parameter(Mandatory=$true,Position=0,ParameterSetName='LoadedModule',ValueFromPipelineByPropertyName=$true)]
[string]
$Name,
# The order in which to display the commands
[Parameter(Position=2)]
[string[]]
$CommandOrder,
# The Google Analytics ID used for the module
[string]
$AnalyticsId,
# The directory where the generated module will be stored.
# If no directory is specified, the module will be put in Inetpub\wwwroot\ModuleName
[string]
$OutputDirectory,
# If set, will overwrite files found in the output directory
[Switch]
$Force,
# If set, will allow the module to be downloaded
[Parameter(Position=1)]
[switch]$AllowDownload,
# If set, will make changes to the web.config file to work for Intranet sites (anonymous authentication will be disabled, and windows authentication will be enabled).
[Switch]$AsIntranetSite,
# The Kerberos realm to use for authentication.
# Only works with -AsIntranetSite.
# If provided, Kerberos authentication will be used instead of NTLM.
# This is both faster, and more secure.
[string]$Realm,
# If provided, will run the site under an app pool with the credential
[Management.Automation.PSCredential]
$AppPoolCredential,
# The port an intranet site should run on.
[Uint32]$Port,
# If a download URL is present, a download link will redirect to that URL.
[uri]$DownloadUrl,
# If set, the blog page will become the homepage of the module
[Switch]$AsBlog,
# If set, will add a URL rewriter rule to accept any URL that is not a real file.
[Switch]$AcceptAnyUrl,
# If this is set, will use this module URL as the module service URL.
[Uri]$ModuleUrl,
# If set, will render a CSS style
[Hashtable]$Style,
# If set, will create appSettings in a web.config file. This can be used to store common settings, like connection data.
[Hashtable]$ConfigSetting = @{},
# The margin on either side of the module content. Defaults to 7.5%.
[ValidateRange(0,100)]
[Double]
$MarginPercent = 3,
# The margin on the left side of the module content. Defaults to 7.5%.
[ValidateRange(0,100)]
[Double]
$MarginPercentLeft = 3,
# The margin on the left side of the module content. Defaults to 7.5%.
[ValidateRange(0,100)]
[Double]
$MarginPercentRight = 3,
# The schematics used to produce the module service.
# Schematics let you quickly and easily give a look or feel around data or commands, and let you parameterize your deployment with the pipeworks manifest.
[Alias('Schematic')]
[string[]]
$UseSchematic,
# If set, will run commands in a runspace for each user. If not set, users will run in a pool
[Switch]
$IsolateRunspace,
# The size of the runspace pool that will handle request. The more runspaces in the pool, the more concurrent users
[Uint16]
$PoolSize = 4,
# If set, will reset IIS
[Switch]
$IISReset,
# The maximum amount of that a page can run before it times out.
[Timespan]
$ExecutionTimeout = [Timespan]::FromSeconds(120),
# The maximum request length.
[Uint32]
$MaximumRequestLength = 640kb,
# If set, will show the default browser when the conversion is complete
[Switch]
$Show,
# If provided, will visit this URL after the conversion is complete.
[Uri]
[Alias('Page', 'ShowPage')]
$Do,
# If set, will run as a background job
[Switch]
$AsJob,
# If provided, will run as a background job, with the throttle being the maximum number of background jobs
[Uint32]
$Throttle,
# The amount of time static content will be cached for. By default, one week.
[Timespan]
$CacheStaticContentFor = [Timespan]::FromDays(7),
# If set, will not clean the output directory. If you are trying to nest multiple pipeworks sites, this would be the way to go.
[Switch]
$DoNotClean,
# If set, the module will be assumed to be nested beneath another module, and no DefaultDocument will be added to the web.config
[Switch]
$IsNested
)
begin {
# First up we define a lot of code that will be used throughout any module service.
#region AsJobOrElevate
# Drop into (almost) any script to let it be run as a background job, or auto-elevate to an admin.
$asJobOrElevate = {
param($CommandInfo, [switch]$OnlyCommand, [string[]]$AdditionalModules, [Hashtable]$Parameter, [Switch]$RequireAdmin)
$currentUser = [Security.Principal.WindowsIdentity]::GetCurrent()
$isAdmin = (New-Object Security.Principal.WindowsPrincipal $currentUser).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
if ($AsJob -or $Throttle -or (-not $isAdmin) -and $requireAdmin) {
if ($onlyCommand) {
$AdditionalModules = $AdditionalModules | Select-Object -Unique
$myDefinition = [ScriptBLock]::Create("
$(if ($AdditionalModules) {
"
Import-Module '$($AdditionalModules -join ("','"))'
"})
function $commandInfo {
$($commandInfo | Select-Object -ExpandProperty Definition)
}
")
} else {
$myModule = $CommandInfo.ScriptBlock.Module
$AdditionalModules += $myModule | Split-Path
$AdditionalModules += $myModule.RequiredModules | Split-Path
$AdditionalModules = $AdditionalModules | Select-Object -Unique
$myDefinition = [ScriptBLock]::Create("
$(if ($AdditionalModules) {
"
Import-Module '$($AdditionalModules -join ("','"))'
"})
")
}
$null = $Parameter.Remove('AsJob')
$null = $Parameter.Remove('Throttle')
$null = $Parameter.Remove('RequireAdmin')
$myJob= [ScriptBLock]::Create("" + {
param([Hashtable]$parameter)
} + $myDefinition + "
$commandInfo `@parameter
")
if ($Throttle) {
$jobLaunched= $false
do {
if ($myJobs) {
$myJobs |
Receive-Job
}
$runningJobs = $myJobs |
Where-Object { $_.State -ne 'Running' }
if ($runningJobs) {
$runningJobs |
Remove-Job -Force
}
if ($myJobs.Count -lt $throttle) {
$null = Start-Job -Name "${MyCmd}_Background_Job" -ScriptBlock $myJob -ArgumentList $Parameter
$JobLaunched = $true
}
$myJobs = Get-Job -Name "${MyCmd}_Background_Job" -ErrorAction SilentlyContinue
Write-Progress "Waiting for Jobs to Complete" "$($myJobs.Count) Running" -Id $ProgressId
} until ($jobLaunched)
$myJobs = Get-Job -Name "${MyCmd}_Background_Job" -ErrorAction SilentlyContinue
$myJobs |
Wait-Job |
Receive-Job
return
} elseif ($asJob) {
return Start-Job -ScriptBlock $myJob -ArgumentList $Parameter -Name "${CommandInfo}_Background_Job"
} elseif ((-not $isAdmin) -and $RequireAdmin) {
$fullCommand =
"
`$parameter = $(Write-PowerShellHashtable -InputObject $parameter)
& { $myJob } `$parameter
"
$encodedCommand = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($fullCommand))
return Start-Process powershell -Verb Runas -ArgumentList '-encodedCommand', $encodedCommand -PassThru
}
}
}
#endregion AsJobOrElevate
# All command services have to have a lot packed into each runspace, so a bit has to happen to set things up
# - An InitialSessionState has to be created for the new runspace
# - Potentially harmful or useless low-rights commands are removed from the runspace
# - "Common" Functions are embedded into each handler
#region ResolveFinalUrl
# This allows us to determine the real URL the service is being called by, including parts from URL redirection
$resolveFinalUrl = {
# The tricky part is resolving the real URL of the service.
# Split out the protocol
$resolveUrlStartedAt = [DateTime]::Now
$protocol = $request['Server_Protocol'].Split("/", [StringSplitOptions]::RemoveEmptyEntries)[0]
# And what it thinks it called the server
$serverName= $request['Server_Name']
$port = $request.Url.Port
# And the relative path beneath that URL
$shortPath = [IO.Path]::GetDirectoryName($request['PATH_INFO'])
# Put them all together
if (($protocol -eq 'http' -and $port -eq 80) -or
($protocol -eq 'https' -and $port -eq 443)) {
$remoteCommandUrl =
$Protocol + '://' + $ServerName.Replace('\', '/').TrimEnd('/') + '/' + $shortPath.Replace('\','/').TrimStart('/')
} else {
$remoteCommandUrl =
$Protocol + '://' + $ServerName.Replace('\', '/').TrimEnd('/') + ':' + $port + '/' + $shortPath.Replace('\','/').TrimStart('/')
}
# Now, if the pages was anything but Default, add the .ashx reference
$finalUrl =
if ($request['Url'].EndsWith("Default.ashx", [StringComparison]"InvariantCultureIgnoreCase")) {
$u = $request['Url'].ToString()
$remoteCommandUrl.TrimEnd("/") + "/"
# $remoteCommandUrl.TrimEnd("/") + $u.Substring($u.LastIndexOf("/"))
} elseif ($request['Url'].EndsWith("Module.ashx", [StringComparison]"InvariantCultureIgnoreCase")) {
$u = $request['Url'].ToString()
$remoteCommandUrl.TrimEnd("/") + $u.Substring($u.LastIndexOf("/"))
} else {
$remoteCommandUrl.TrimEnd("/") + "/"
}
$fullUrl = "$($request.Url)"
if ($request -and $request.Params -and $request.Params["HTTP_X_ORIGINAL_URL"]) {
#region Determine the Relative Path, Full URL, and Depth
$originalUrl = $context.Request.ServerVariables["HTTP_X_ORIGINAL_URL"]
$urlString = $request.Url.ToString().TrimEnd("/")
$pathInfoUrl = $urlString.Substring(0,
$urlString.LastIndexOf("/"))
$protocol = ($request['Server_Protocol'].Split("/",
[StringSplitOptions]"RemoveEmptyEntries"))[0]
$serverName= $request['Server_Name']
$port= $request.Url.Port
$fullOriginalUrl =
if (($Protocol -eq 'http' -and $port -eq 80) -or
($Protocol -eq 'https' -and $port -eq 443)) {
$protocol+ "://" + $serverName + $originalUrl
} else {
$protocol+ "://" + $serverName + ':' + $port + $originalUrl
}
$rindex = $fullOriginalUrl.IndexOf($pathInfoUrl, [StringComparison]"InvariantCultureIgnoreCase")
$relativeUrl = $fullOriginalUrl.Substring(($rindex + $pathInfoUrl.Length))
$rootUrl = $fullOriginalUrl.Substring(0, $pathInfoUrl.Length)
if ($relativeUrl -like "*/*") {
$depth = @($relativeUrl -split "/" -ne "").Count - 1
if ($fullOriginalUrl.EndsWith("/")) {
$depth++
}
} else {
$depth = 0
}
$RelativeDepth = "../" * $depth
#endregion Determine the Relative Path, Full URL, and Depth
$fullUrl = $fullOriginalUrl
}
if (-not $rootUrl) {
$rootUrl = $fullurl.Substring(0,
$fullUrl.LastIndexOf("/"))
}
$serviceUrl = $fullUrl
$timeSpentResolvingURL = [DateTime]::now - $resolveUrlStartedAt
}
#endregion ResolveFinalUrl
#region UnpackItem
# This allows us to take items with compressed data and expand them
$unpackItem = {
$item = $_
$item.psobject.properties |
Where-Object {
('Timestamp', 'RowKey', 'TableName', 'PartitionKey' -notcontains $_.Name) -and
(-not "$($_.Value)".Contains(' '))
}|
ForEach-Object {
try {
$expanded = Expand-Data -CompressedData $_.Value
$item | Add-Member NoteProperty $_.Name $expanded -Force
} catch{
Write-Verbose $_
}
}
$item.psobject.properties |
Where-Object {
('Timestamp', 'RowKey', 'TableName', 'PartitionKey' -notcontains $_.Name) -and
(-not "$($_.Value)".Contains('<'))
}|
ForEach-Object {
try {
$fromMarkdown = ConvertFrom-Markdown -Markdown $_.Value
$item | Add-Member NoteProperty $_.Name $fromMarkdown -Force
} catch{
Write-Verbose $_
}
}
$item
}
#endregion UnpackItem
#region RefreshLatest
$refreshLatest = {
if (-not ($pipeworksManifest.Table -and $pipeworksManifest.Table.StorageAccountSetting -and $pipeworksManifest.Table.StorageKeySetting)) {
throw 'The Pipeworks manifest must include three settings in order to retrieve items from table storage: Table, TableStorageAccountSetting, and TableStorageKeySetting'
return
}
$storageAccount = (Get-WebConfigurationSetting -Setting $pipeworksManifest.Table.StorageAccountSetting)
$storageKey = (Get-WebConfigurationSetting -Setting $pipeworksManifest.Table.StorageKeySetting)
$latest =
Search-AzureTable -TableName $pipeworksManifest.Table.Name -Filter "PartitionKey eq '$PartitionKey'" -Select Timestamp, DatePublished, PartitionKey, RowKey -StorageAccount $storageAccount -StorageKey $storageKey |
Sort-Object -Descending {
if ($_.DatePublished) {
[DateTime]$_.DatePublished
} else {
[DateTime]$_.Timestamp
}
} |
Select-Object -First 1 |
Get-AzureTable -TableName $pipeworksManifest.Table.Name
}
#endregion RefreshLatest
# Writing the handler for a command actually involves writing several handlers,
# so we'll make this it's own little inline tool.
$writeSimpleHandler = {
param($cSharp, [Switch]$ShareRunspace, [Uint16]$PoolSize, [Switch]$ImportsPipeworks, [string[]]$EmbeddedCommand)
# Blacklist "bad" functions, and directory traversal
$functionBlackList = 65..90 |
ForEach-Object -Begin {
"ImportSystemModules", "Disable-PSRemoting", "Restart-Computer", "Clear-Host", "cd..", "cd\\", "more"
} -Process {
[string][char]$_ + ":"
}
if (-not $script:FunctionsInEveryRunspace) {
$script:FunctionsInEveryRunspace = 'ConvertFrom-Markdown', 'Confirm-Person', 'Get-Person', 'Get-Web', 'Get-PipeworksManifest', 'Get-WebConfigurationSetting', 'Get-FunctionFromScript', 'Get-Walkthru',
'Get-WebInput', 'New-RssItem', 'Invoke-WebCommand', 'Out-RssFeed', 'Request-CommandInput', 'New-Region', 'New-WebPage', 'Out-Html',
'Write-Css', 'Write-Host', 'Write-Link', 'Write-ScriptHTML', 'Write-WalkthruHTML', 'Write-PowerShellHashtable', 'Compress-Data',
'Expand-Data', 'Import-PSData', 'Export-PSData', 'ConvertTo-ServiceUrl', 'Get-SecureSetting', 'Search-Engine', 'Get-Hash'
}
$embedSection = ""
if (-not $ImportsPipeworks) {
if (-not $EmbeddedCommand) {
$EmbeddedCommand = $script:FunctionsInEveryRunspace
}
$EmbeddedCommand = $EmbeddedCommand | Select-Object -Unique
$embedSection += foreach ($func in (Get-Command -Name $EmbeddedCommand -CommandType Function)) {
@"
string compressed$($func.Name.Replace('-', ''))Defintion = "$(Compress-Data -String $func.Definition.ToString())";
byte[] binaryDataFor$($func.Name.Replace('-', '')) = System.Convert.FromBase64String(compressed$($func.Name.Replace('-', ''))Defintion);
System.IO.MemoryStream memoryStreamFor$($func.Name.Replace('-', '')) = new System.IO.MemoryStream();
memoryStreamFor$($func.Name.Replace('-', '')).Write(binaryDataFor$($func.Name.Replace('-', '')), 0, binaryDataFor$($func.Name.Replace('-', '')).Length);
memoryStreamFor$($func.Name.Replace('-', '')).Seek(0, 0);
System.IO.Compression.GZipStream decompressorFor$($func.Name.Replace('-', '')) =
new System.IO.Compression.GZipStream(memoryStreamFor$($func.Name.Replace('-', '')), System.IO.Compression.CompressionMode.Decompress);
System.IO.StreamReader readerFor$($func.Name.Replace('-', '')) = new System.IO.StreamReader(decompressorFor$($func.Name.Replace('-', '')));
string decompressedDefinitionFor$($func.Name.Replace('-', '')) = readerFor$($func.Name.Replace('-', '')).ReadToEnd();
SessionStateFunctionEntry $($func.Name.Replace('-',''))Command = new SessionStateFunctionEntry(
"$($func.Name)", decompressedDefinitionFor$($func.Name.Replace('-', ''))
);
iss.Commands.Add($($func.Name.Replace('-',''))Command);
memoryStreamFor$($func.Name.Replace('-', '')).Close();
memoryStreamFor$($func.Name.Replace('-', '')).Dispose();
decompressorFor$($func.Name.Replace('-', '')).Close();
decompressorFor$($func.Name.Replace('-', '')).Dispose();
readerFor$($func.Name.Replace('-', '')).Close();
"@
}
# Web handlers are essentially embedded C#, compiled on their first use. The webCommandSequence class,
# defined within this quite large herestring, is a bridge used to invoke PowerShell within a web handler.
}
$webCmdSequence = @"
public class WebCommandSequence {
public static InitialSessionState InitializeRunspace(string[] module) {
InitialSessionState iss = InitialSessionState.CreateDefault();
if (module != null) {
iss.ImportPSModule(module);
}
$embedSection
string[] commandsToRemove = new String[] { "$($functionBlacklist -join '","')"};
foreach (string cmdName in commandsToRemove) {
iss.Commands.Remove(cmdName, null);
}
return iss;
}
public static void InvokeScript(string script,
HttpContext context,
object arguments,
bool throwError,
bool shareRunspace) {
PowerShell psCmd = PowerShell.Create();
psCmd.Commands.Clear();
bool justLoaded = false;
Runspace runspace;
RunspacePool runspacePool;
PSInvocationSettings invokeWithHistory = new PSInvocationSettings();
invokeWithHistory.AddToHistory = true;
PSInvocationSettings invokeWithoutHistory = new PSInvocationSettings();
invokeWithHistory.AddToHistory = false;
if (! shareRunspace) {
if (context.Session["UserRunspace"] == null) {
justLoaded = true;
InitialSessionState iss = WebCommandSequence.InitializeRunspace(null);
Runspace rs = RunspaceFactory.CreateRunspace(iss);
rs.ApartmentState = System.Threading.ApartmentState.STA;
rs.ThreadOptions = PSThreadOptions.ReuseThread;
rs.Open();
psCmd.Runspace = rs;
context.Session.Add("UserRunspace",psCmd.Runspace);
psCmd.
AddCommand("Set-ExecutionPolicy", false).
AddParameter("Scope", "Process").
AddParameter("ExecutionPolicy", "Bypass").
AddParameter("Force", true).
Invoke(null, invokeWithoutHistory);
psCmd.Commands.Clear();
}
runspace = context.Session["UserRunspace"] as Runspace;
if (context.Application["Runspaces"] == null) {
context.Application["Runspaces"] = new Hashtable();
}
if (context.Application["RunspaceAccessTimes"] == null) {
context.Application["RunspaceAccessTimes"] = new Hashtable();
}
if (context.Application["RunspaceAccessCount"] == null) {
context.Application["RunspaceAccessCount"] = new Hashtable();
}
Hashtable runspaceTable = context.Application["Runspaces"] as Hashtable;
Hashtable runspaceAccesses = context.Application["RunspaceAccessTimes"] as Hashtable;
Hashtable runspaceAccessCounter = context.Application["RunspaceAccessCount"] as Hashtable;
if (! runspaceAccessCounter.Contains(runspace.InstanceId.ToString())) {
runspaceAccessCounter[runspace.InstanceId.ToString()] = (int)0;
}
runspaceAccessCounter[runspace.InstanceId.ToString()] = ((int)runspaceAccessCounter[runspace.InstanceId.ToString()]) + 1;
runspaceAccesses[runspace.InstanceId.ToString()] = DateTime.Now;
if (! runspaceTable.Contains(runspace.InstanceId.ToString())) {
runspaceTable[runspace.InstanceId.ToString()] = runspace;
}
runspace.SessionStateProxy.SetVariable("Request", context.Request);
runspace.SessionStateProxy.SetVariable("Response", context.Response);
runspace.SessionStateProxy.SetVariable("Session", context.Session);
runspace.SessionStateProxy.SetVariable("Server", context.Server);
runspace.SessionStateProxy.SetVariable("Cache", context.Cache);
runspace.SessionStateProxy.SetVariable("Context", context);
runspace.SessionStateProxy.SetVariable("Application", context.Application);
runspace.SessionStateProxy.SetVariable("JustLoaded", justLoaded);
runspace.SessionStateProxy.SetVariable("IsSharedRunspace", false);
psCmd.Runspace = runspace;
psCmd.AddScript(@"
`$timeout = (Get-Date).AddMinutes(-20)
`$oneTimeTimeout = (Get-Date).AddMinutes(-1)
foreach (`$key in @(`$application['Runspaces'].Keys)) {
if ('Closed', 'Broken' -contains `$application['Runspaces'][`$key].RunspaceStateInfo.State) {
`$application['Runspaces'][`$key].Dispose()
`$application['Runspaces'].Remove(`$key)
continue
}
if (`$application['RunspaceAccessTimes'][`$key] -lt `$Timeout) {
`$application['Runspaces'][`$key].CloseAsync()
continue
}
}
").Invoke();
psCmd.Commands.Clear();
psCmd.AddScript(script, false);
if (arguments is IDictionary) {
psCmd.AddParameters((arguments as IDictionary));
} else if (arguments is IList) {
psCmd.AddParameters((arguments as IList));
}
Collection<PSObject> results = psCmd.Invoke();
} else {
if (context.Application["RunspacePool"] == null) {
justLoaded = true;
InitialSessionState iss = WebCommandSequence.InitializeRunspace(null);
RunspacePool rsPool = RunspaceFactory.CreateRunspacePool(iss);
rsPool.SetMaxRunspaces($PoolSize);
rsPool.ApartmentState = System.Threading.ApartmentState.STA;
rsPool.ThreadOptions = PSThreadOptions.ReuseThread;
rsPool.Open();
psCmd.RunspacePool = rsPool;
context.Application.Add("RunspacePool",rsPool);
/*
// Initialize the pool
Collection<IAsyncResult> resultCollection = new Collection<IAsyncResult>();
for (int i =0; i < $poolSize; i++) {
PowerShell execPolicySet = PowerShell.Create().
AddScript(@"
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass -Force
#INSERTEVERYSECTIONIFNEEDED
", false);
execPolicySet.RunspacePool = rsPool;
resultCollection.Add(execPolicySet.BeginInvoke());
}
foreach (IAsyncResult lastResult in resultCollection) {
if (lastResult != null) {
lastResult.AsyncWaitHandle.WaitOne();
}
}
*/
psCmd.Commands.Clear();
}
psCmd.RunspacePool = context.Application["RunspacePool"] as RunspacePool;
string newScript = @"param(`$Request, `$Response, `$Server, `$session, `$Cache, `$Context, `$Application, `$JustLoaded, `$IsSharedRunspace, [Parameter(ValueFromRemainingArguments=`$true)]`$args)
" + script;
psCmd.AddScript(newScript, false);
if (arguments is IDictionary) {
psCmd.AddParameters((arguments as IDictionary));
} else if (arguments is IList) {
psCmd.AddParameters((arguments as IList));
}
psCmd.AddParameter("Request", context.Request);
psCmd.AddParameter("Response", context.Response);
psCmd.AddParameter("Session", context.Session);
psCmd.AddParameter("Server", context.Server);
psCmd.AddParameter("Cache", context.Cache);
psCmd.AddParameter("Context", context);
psCmd.AddParameter("Application", context.Application);
psCmd.AddParameter("JustLoaded", justLoaded);
psCmd.AddParameter("IsSharedRunspace", true);
Collection<PSObject> results;
try {
results = psCmd.Invoke();
} catch (Exception ex) {
if (
(String.Compare(ex.GetType().FullName, "System.Management.Automation.ParameterBindingValidationException") == 0) ||
(String.Compare(ex.GetType().FullName, "System.Management.Automation.RuntimeException") == 0)
) {
// Parameter validation exception: clean it up a little.
ErrorRecord errRec = ex.GetType().GetProperty("ErrorRecord").GetValue(ex, null) as ErrorRecord;
if (errRec != null) {
try {
context.Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
} catch {
}
context.Response.Write("<span class='ui-state-error' color='red'>" + errRec.InvocationInfo.PositionMessage + "</span><br/>");
}
} else {
throw ex;
}
}
psCmd.Dispose();
}
foreach (ErrorRecord err in psCmd.Streams.Error) {
if (throwError) {
if (err.Exception != null) {
if (err.Exception.GetType().GetProperty("ErrorRecord") != null) {
ErrorRecord errRec = err.Exception.GetType().GetProperty("ErrorRecord").GetValue(err.Exception, null) as ErrorRecord;
if (errRec != null) {
//context.Response.StatusCode = (int)System.Net.HttpStatusCode.PreconditionFailed;
//context.Response.StatusDescription = errRec.InvocationInfo.PositionMessage;
context.Response.Write("<span class='ui-state-error' style='line-height:200%' color='red'>" + err.Exception.ToString() + errRec.InvocationInfo.PositionMessage + "</span><br/>");
}
//context.Response.Flush();
} else {
context.AddError(err.Exception);
}
}
} else {
context.Response.Write("<span class='ui-state-error' style='line-height:200%' color='red'>" + err.Exception.ToString() + err.InvocationInfo.PositionMessage + "</span><br/>");
}
}
if (psCmd.InvocationStateInfo.Reason != null) {
if (throwError) {
context.AddError(psCmd.InvocationStateInfo.Reason);
} else {
context.Response.Write("<span class='ui-state-error' style='line-height:200%' color='red'>" + psCmd.InvocationStateInfo.Reason + "</span>");
}
}
}
}
"@
$webCommandSequence = $webCmdSequence
if ($pipeworksManifest.Every -and $pipeworksManifest.Every -is [Hashtable]) {
$everySection = ""
$n = 1
foreach ($kv in $pipeworksManifest.Every.GetEnumerator()) {
$interval = $kv.Key
$everyAction = $kv.Value
$everySection += "
`$everyTimer${n} = New-Object Timers.Timer -Property @{
Interval = ([Timespan]'$interval').TotalMilliseconds
}
`$global:firstPulse = Get-Date
Register-ObjectEvent -InputObject `$everyTimer${n} -EventName Elapsed -SourceIdentifier EveryAction${n} -Action {
$everyAction
}
`$everyTimer${n}.Start()
"
$n++
}
$webCommandSequence = $webCommandSequence.Replace('#INSERTEVERYSECTIONIFNEEDED', $everySection.Replace('"', '""'))
}
@"
<%@ WebHandler Language="C#" Class="Handler" %>
<%@ Assembly Name="System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
using System;
using System.Web;
using System.Web.SessionState;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
$webCommandSequence
public class Handler : IHttpHandler, IRequiresSessionState {
public void ProcessRequest (HttpContext context) {
$cSharp
}
public bool IsReusable {
get {
return true;
}
}
}
"@
}
}
process {
$theModule = Get-Module $name
$theModulePaths = @($theModule| Split-Path)
$theModulePaths += @($theModule.RequiredModules | Split-Path)
$launched = . $asJobOrElevate $MyInvocation.MyCommand -additionalModules $theModulePaths -Parameter $psBoundParameters -RequireAdmin
if ($launched) { return $launched}
if ($psCmdlet.ParameterSetName -eq 'LoadedModule') {
$module = Get-Module $name | Select-Object -First 1
if (-not $module ) { return }
# Skip "accidental" modules
if ($module.Path -like "*.ps1") { return }
$global:PipeworksManifest = $null
if (-not $psBoundParameters.outputDirectory) {
$outputDirectory = "${env:SystemDrive}\inetpub\wwwroot\$($Module.Name)\"
$outDirWasSet = $false
} else {
$outDirWasSet = $true
}
if ((Test-Path $outputDirectory) -and (-not $force)) {
Write-Error "$outputDirectory exists, use -Force to overwrite"
return
}
if (-not $DoNotClean) {
Write-Progress "Cleaning Output Directory" "$outputDirectory"
Remove-Item $outputDirectory -Recurse -Force -ErrorVariable Issues
}
$null = New-Item -Path $outputDirectory -Force -ItemType Directory
Push-Location $outputDirectory
$null = New-Item -Path "$outputDirectory\bin" -Force -ItemType Directory
# Urls to Rewrite stores the result. Each handler will need to rewrite several URLs for the functionality to work as expected
$urlsToRewrite = @{}
# To create a web command, we actually need to create several handlers and pages, depending on the options specified.
$moduleNumber = 0
$realModule = $module
foreach ($m in $realModule) {
if (-not $m) { continue }
$moduleRoot = Split-Path $m.Path
$ManifestPath = Join-Path $moduleRoot "$($module.Name).psd1"
if (-not (Test-Path $ManifestPath)) {
"
# Module Manifest autogenerated by PowerShell Pipeworks.
@{
ModuleVersion = 0.1
ModuleToProcess = '$($module.Path | Split-Path -Leaf)'
}" |
Set-Content $manifestPath
}
#region Initialize Pipeworks Manifest
$pipeworksManifestPath = Join-Path $moduleRoot "$($module.Name).Pipeworks.psd1"
$pipeworksManifest = if (Test-Path $pipeworksManifestPath) {
try {
& ([ScriptBlock]::Create(
"data -SupportedCommand Add-Member, New-WebPage, New-Region, Write-CSS, Write-Ajax, Out-Html, Write-Link { $(
[ScriptBlock]::Create([IO.File]::ReadAllText($pipeworksManifestPath))
)}"))
} catch {
Write-Error "Could not read pipeworks manifest"
}
}
if (-not $pipeworksManifest) {
$pipeworksManifest = @{
Pages = @{}
Posts = @{}
WebCommands = @{}
Assets = @{}
Javascript = @{}
Download = @{}
CSS = @{}
}
}
if ($pipeworksManifest.Css) {
foreach ($cssItem in $pipeworksManifest.Css.GetEnumerator()) {
if ($cssItem.Value -like "*.less") {
if ($cssItem.Value -like "http*:*") {
# Public LESS file, download and compile
$lessCssFile = Get-Web -Url "$($cssItem.Value)" -UseWebRequest
$compiledLess = Use-Less -LessCss $lessCssFile
$lessDest = Join-Path "$moduleRoot\CSS" (([uri]$cssItem.Value).Segments[-1] -ireplace "\.less", ".css")
if (-not (Test-Path "$moduleRoot\CSS")) {
$null = New-Item -ItemType Directory -Path "$moduleRoot\CSS" -Force
}
[IO.File]::WriteAllText($lessDest, $compiledLess)
} elseif ($cssItem.Value -like "/*") {
# Private LESS file, resolve and compile
$lessCssFile = [IO.File]::ReadAllText((Join-Path $moduleRoot $cssItem.Value))
$compiledLess = Use-Less -LessCss $lessCssFile
$lessDest = (Join-Path $moduleRoot $cssItem.Value) -ireplace "\.less", ".css"
[IO.File]::WriteAllText($lessDest, $compiledLess)
}
}
}
}
#region Inherit Settings from the Pipeworks Manifest
if (-not ($Style -and $PipeworksManifest.Style)) {
$Style = $PipeworksManifest.Style
}
# If there's no CSS style set, create a default one
if (-not $Style) {
$Style = @{
Body = @{
'Font-Family' = "'Segoe UI', 'Segoe UI Symbol', Helvetica, Arial, sans-serif"
}
}
}
if (-not $psBoundParameters.MarginPercent -or ($psBoundParameters.MarginPercentLeft -and $psBoundParameters.MarginPercentRight)) {
$marginPercentLeftString = "3%"
$marginPercentRightString= "3%"
} else {
if ($psBoundParameters.MarginPercent) {
$marginPercentLeftString = $MarginPercent + "%"
$marginPercentRightString = $MarginPercent + "%"
} else {
$marginPercentLeftString = $MarginPercentLeft+ "%"
$marginPercentRightString = $MarginPercentRight+ "%"
}
}
if ($pipeworksManifest.SecureSetting) {