forked from mmessano/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathPoshCode.psm1
1543 lines (1442 loc) · 55.7 KB
/
PoshCode.psm1
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
####################################################################################################
## Script Name: PoshCode Module
## Created On:
## Author: Joel 'Jaykul' Bennett
## File: PoshCode.psm1
## Usage:
## Version: 3.13
## Purpose: Provides cmdlets for working with scripts from the PoshCode Repository:
## Get-PoshCodeUpgrade - get the latest version of this script from the PoshCode server
## Get-PoshCode - Search for and download code snippets
## New-PoshCode - Upload new code snippets
## Get-WebFile - Download
## Requirements: PowerShell Version 2
## Last Updated: 07/14/2010
## History:
## 3.13 2010-08-04 - Fixed proxy credentials for download (oops)
## - Fixed WebException handling (e.g.: 404 errors) on Get-WebFile (only report one error, and make it nicer)
## - Fixed test for $filename so it doesn't throw if $filename is empty
## 3.12 2010-07-14 - Complete help documentation for the last two public functions.
## 3.11 2010-06-08 - Add code for proxy credentials at Kirk Munro's suggestion.
## 3.10 2009-11-08 - Fix a typo bug in Get-PoshCode
## 3.9 2009-10-02 - Put back the fixed NTFS Streams
## 3.8 2009-08-04 - Fixed PoshCodeUpgrade for CTP3+ and added secondary cert
## 3.7 2009-07-29 - Remove NTFS Streams
## 3.6 2009-05-04 - Documentation Rewrite
##
####################################################################################################
#requires -version 2.0
Set-StrictMode -Version Latest
$PoshCode = "http://PoshCode.org/" |
Add-Member -type NoteProperty -Name "UserName" -Value "Anonymous" -Passthru |
Add-Member -type ScriptProperty -Name "ScriptLocation" -Value {
$module = $null
Get-Module PoshCode | Select -expand Path -EA "SilentlyContinue" | Tee -var module
if(!$module) { # Try finding it by path, since it's not loaded as "PoshCode"
Get-Module | ? {$_.Name -match "^$([RegEx]::Escape($PsScriptRoot))"} | Select -expand Path
}
} -Passthru |
Add-Member -type ScriptProperty -Name "ModuleName" -Value {
if( Get-Module PoshCode ) { "PoshCode" } else {
Get-Module | ? {$_.Name -match "^$([RegEx]::Escape($PsScriptRoot))"} | Select -expand Name
}
} -Passthru |
Add-Member -type NoteProperty -Name "ScriptVersion" -Value 3.13 -Passthru |
Add-Member -type NoteProperty -Name "ApiVersion" -Value 1 -Passthru
function New-PoshCode {
<#
.SYNOPSIS
Uploads a script to PoshCode
.DESCRIPTION
Uploads code to the PowerShell Script Repository and returns the url for you.
.LINK
http://www.poshcode.org
.EXAMPLE
C:\PS>Get-Content MyScript.ps1 | New-PoshCode "An example for you" "This is just to show how to do it"
This command gets the content of MyScript.ps1 and passes it to New-Poshcode which then posts it to poshcode.org with the specified title and description.
.PARAMETER Path
Specifies the path to an item.
.PARAMETER Description
Sets the free-text summary of the script that will be displayed on the poshcode page for the script.
.PARAMETER Author
Specifies the author of the script that is being submitted.
.PARAMETER Language
Specifies the language of the script that is being submitted.
.PARAMETER Keep
Specifies how long to keep scripts on the poshcode.org site. Possible values are 'day', 'month', or 'forever'.
.PARAMETER Title
Specifies the title of the script that is being submitted.
.PARAMETER URL
Overrides the default PoshCode url, to allow posting to other Pastebin sites.
.NOTES
History:
v 3.1 - Fixed the $URL parameter so that it's settable again. *This* function should work on any pastebin site
v 3.0 - Renamed to New-PoshCode.
- Removed the -Permanent switch, since this is now exclusive to the permanent repository
v 2.1 - Changed some defaults
- Added "PermanentPosh" switch ( -P ) to switch the upload to the PowerShellCentral repository
v 2.0 - works with "pastebin" (including posh.jaykul.com/p/ and PowerShellCentral.com/scripts/)
v 1.0 - Worked with a special pastebin
#>
[CmdletBinding()]
PARAM(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[string]$Path
,
[Parameter(Position=5, Mandatory=$true)]
[string]$Description
,
[Parameter(Mandatory=$true, Position=10)]
[string]$Author
,
[Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("BaseName","Name")]
[string]$Title
,
[Parameter(Position=15)]
[PoshCodeLanguage]$Language="posh"
,
[Parameter(Position=20, Mandatory=$false)]
[ValidateScript({ if($_ -match "^[dmf]") { return $true } else { throw "Please specify 'day', 'month', or 'forever'" } })]
[string]$Keep="f"
,
[Parameter()]
[int]$Parent = 0
,
[Parameter(Mandatory=$false)]
[string]$url= $($PoshCode)
)
BEGIN {
$null = [Reflection.Assembly]::LoadWithPartialName("System.Web")
[string]$data = ""
[string]$meta = ""
if($language) {
$meta = "format=" + [System.Web.HttpUtility]::UrlEncode($language)
# $url = $url + "?" +$lang
} else {
$meta = "format=text"
}
if($Parent) {
$meta = $meta + "&parent_pid=$Parent"
}
# Note how simplified this is by
switch -regex ($Keep) {
"^d" { $meta += "&expiry=d" }
"^m" { $meta += "&expiry=m" }
"^f" { $meta += "&expiry=f" }
}
if($Description) {
$meta += "&descrip=" + [System.Web.HttpUtility]::UrlEncode($Description)
} else {
$meta += "&descrip="
}
$meta += "&poster=" + [System.Web.HttpUtility]::UrlEncode($Author)
function Send-PoshCode ($meta, $title, $data, $url= $($PoshCode)) {
$meta += "&paste=Send&posttitle=" + [System.Web.HttpUtility]::UrlEncode($Title)
$data = $meta + "&code2=" + [System.Web.HttpUtility]::UrlEncode($data)
$request = [System.Net.WebRequest]::Create($url)
$request.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
if ($request.Proxy -ne $null) {
$request.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
}
$request.ContentType = "application/x-www-form-urlencoded"
$request.ContentLength = $data.Length
$request.Method = "POST"
$post = new-object IO.StreamWriter $request.GetRequestStream()
$post.Write($data)
$post.Flush()
$post.Close()
# $reader = new-object IO.StreamReader $request.GetResponse().GetResponseStream() ##,[Text.Encoding]::UTF8
# write-output $reader.ReadToEnd()
# $reader.Close()
write-output $request.GetResponse().ResponseUri.AbsoluteUri
$request.Abort()
}
}
PROCESS {
$EAP = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
if(Test-Path $Path -PathType Leaf) {
$ErrorActionPreference = $EAP
Write-Verbose $Path
Write-Output $(Send-PoshCode $meta $Title $([string]::join("`n",(Get-Content $Path))) $url)
} elseif(Test-Path $Path -PathType Container) {
$ErrorActionPreference = $EAP
Write-Error "Can't upload folders yet: $Path"
} else { ## Todo, handle folders?
$ErrorActionPreference = $EAP
if(!$data -and !$Title){
$Title = Read-Host "Give us a title for your post"
}
$data += "`n" + $Path
}
}
END {
if($data) {
Write-Output $(Send-PoshCode $meta $Title $data $url)
}
}
}
function Get-PoshCode {
<#
.SYNOPSIS
Search for and/or download scripts from PoshCode.org
.DESCRIPTION
Search PoshCode.org by search terms, and returns a list of results, Or download a specific script by ID and output the contents or save to file.
.LINK
http://www.poshcode.org
.EXAMPLE
C:\PS>Get-PoshCode Authenticode
This command searches the repository for scripts dealing with Authenticode, and list the results
Normally, you will take one of those IDs and do this:
.EXAMPLE
C:\PS>Get-PoshCode 456
This command will download the script with the ID of 456 and save it to file (based on it's name/contents)
.EXAMPLE
C:\PS>Get-PoshCode 456 -passthru
Thi command outputs the contents of that script into the pipeline, so eg:
(Get-PoshCode 456 -passthru) -replace "AuthenticodeSignature","SillySig"
.EXAMPLE
C:\PS>Get-PoshCode 456 $ProfileDir\Authenticode.psm1
This command downloads the script saving it as the name specified.
.EXAMPLE
C:\PS>Get-PoshCode SCOM | Get-PoshCode
This command searches the repository for all scripts about SCOM, and then downloads them!
.PARAMETER Path
Specifies the path to an item.
.PARAMETER Description
Sets the free-text summary of the script that will be displayed on the poshcode page for the script.
.PARAMETER Author
Specifies the author of the script that is being submitted.
.PARAMETER Language
Specifies the language of the script that is being submitted.
.PARAMETER Keep
Specifies how long to keep scripts on the poshcode.org site. Possible values are 'day', 'month', or 'forever'.
.PARAMETER Title
Specifies the title of the script that is being submitted.
.PARAMETER URL
.NOTES
All search terms are automatically surrounded with wildcards.
History:
v 3.10 - Fixed a typo
v 3.9 - Fixed and put back the Set-DownloadFlag code
v 3.7 - Removed the Set-DownloadFlag code because it was throwing on Windows 7:
"Attempted to read or write protected memory."
v 3.4 - Add "-Language" parameter to force PowerShell only, fix upgrade to leave INVALID as .psm1
v 3.2 - Add "-Upgrade" switch to cause the script to upgrade itself.
v 3.1 - Add "Huddled.PoshCode.ScriptInfo" to TypeInfo, so it can be formatted by a ps1xml
- Add ConvertTo-Module function to try to rename .ps1 scripts to .psm1
- Fixed exceptions thrown by searches which return no results
- Removed the auto-wildcards!!!!
NOTE: to get the same results as before you must now put * on the front and end of searches
This is so that searches on the website work the same as searches here...
My intention is to improve the website's search instead of leaving this here.
NOTE: the website currently will not search for words less than 4 characters long
v 3.0 - Working against the new RSS-based API
- And using ParameterSets, which work in CTP2
v 2.0 - Combined with Find-Poshcode into a single script
v 1.0 - Working against our special pastebin
#>
[CmdletBinding(DefaultParameterSetName="Download")]
PARAM(
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Search")]
[string]$Query
,
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="Download" )]
[int]$Id
,
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Upgrade")]
[switch]$Upgrade
,
[Parameter(Position=1, Mandatory=$false, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[string]$SaveAs
,
[Parameter(Position=2, Mandatory=$false, ValueFromPipelineByPropertyName=$true)]
[ValidateSet('text','asp','bash','cpp','csharp','posh','vbnet','xml','all')]
[string]$Language="posh"
,
[switch]$InBrowser
,
[switch]$Passthru
,
[Parameter(Mandatory=$false)][string]$url= $($PoshCode)
)
PROCESS {
Write-Debug "ParameterSet Name: $($PSCmdlet.ParameterSetName)"
if($Language -eq 'all') { $Language = "" }
switch($PSCmdlet.ParameterSetName) {
"Search" {
$results = @(([xml](Get-WebFile "$($url)api$($PoshCode.ApiVersion)/$($query)&lang=$($Language)" -passthru)).rss.channel.GetElementsByTagName("item"))
if($results.Count -eq 0 ) {
Write-Host "Zero Results for '$query'" -Fore Red -Back Black
}
else {
$results | Select @{ n="Id";e={$($_.link -replace $url,'') -as [int]}},
@{n="Title";e={$_.title}},
@{n="Author";e={$_.creator}},
@{n="Date";e={$_.pubDate }},
@{n="Link";e={$_.guid.get_InnerText() }},
@{n="Web";e={$_.Link}},
@{n="Description";e={"$($_.description.get_InnerText())`n" }} |
ForEach { $_.PSObject.TypeNames.Insert( 0, "Huddled.PoshCode.ScriptInfo" ); $_ }
}
}
"Download" {
if(!$InBrowser) {
if($Passthru) {
Get-WebFile "$($url)?dl=$id" -Passthru
}
elseif($SaveAs) {
Get-WebFile "$($url)?dl=$id" -fileName $SaveAs | ConvertTo-Module | Set-DownloadFlag -Passthru
}
else {
Get-WebFile "$($url)?dl=$id" | ConvertTo-Module | Set-DownloadFlag -Passthru
}
}
else {
[Diagnostics.Process]::Start( "$($url)$id" )
}
}
"Upgrade" {
Get-PoshCodeUpgrade
}
}
}
}
function Get-PoshCodeUpgrade {
<#
.SYNOPSIS
Downloads a new PoshCode module and archives the old version(s).
.LINK
http://www.poshcode.org
.EXAMPLE
C:\PS>Get-PoshCodeUpgrade
This command gets the most recent version of the PoshCode module
.NOTES
History:
v3.9 - Fixed and put back the Remove-DownloadFlag
v3.8 - Switched "Add-Module" to "Import-Module" to make it CTP3+ compatible.
v3.7 - Removed the Set-DownloadFlag code because it was throwing on Windows 7:
"Attempted to read or write protected memory."
v3.3 - Removes old versions, and checks the signature.
v3.2 - First script version with Upgrade function
#>
[CmdletBinding()]param()
$VersionFile = [IO.Path]::ChangeExtension( $PoshCode.ScriptLocation,
("{0}{1}" -f $PoshCode.ScriptVersion, [IO.Path]::GetExtension($PoshCode.ScriptLocation)))
# Copy it to make sure we don't loose it
Copy-Item $PoshCode.ScriptLocation $VersionFile
# Remove old ones ...
Remove-Item ( [IO.Path]::ChangeExtension( $PoshCode.ScriptLocation,
".*$([IO.Path]::GetExtension( $($PoshCode.ScriptLocation) ))")
) -exclude ([IO.Path]::GetFileName($VersionFile)) -Confirm
# Finally, get the new one
$NewFile = Get-WebFile "$($PoshCode)PoshCode.psm1" -fileName (
[IO.Path]::ChangeExtension( $PoshCode.ScriptLocation, ".INVALID.ps1"))
if( Test-Signature -File $NewFile )
{
Move-Item $NewFile $PoshCode.ScriptLocation -Force -passthru | Remove-DownloadFlag -Passthru
Import-Module $($PoshCode.ModuleName) -Force
}
else {
Write-Error "Signature is Not Valid on new version."
Move-Item $NewFile ([IO.Path]::ChangeExtension( $PoshCode.ScriptLocation, ".INVALID.psm1"))
Get-Item ([IO.Path]::ChangeExtension( $PoshCode.ScriptLocation, ".INVALID.psm1"))
}
}
## Test-Signature - Returns true if the signature is valid OR is signed by:
## "4F8842037D878C1FCDC6FD1313B200449716C353" OR "7DEFA3C6C2138C05AAA135FB8096332DEB9603E1"
function Test-Signature {
[CmdletBinding(DefaultParameterSetName="File")]
PARAM (
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="Signature")]
# We can't actually require the type, or we won't be able to check the fake ones from Joel's Authenticode module
# [System.Management.Automation.Signature]
$Signature
, [Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="File")]
[System.IO.FileInfo]
$File
)
PROCESS {
if($File -and (Test-Path $File -PathType Leaf)) {
$Signature = Get-AuthenticodeSignature $File
}
if(!$Signature) { return $false } else {
$result = $false;
try {
$result = ((($Signature.Status -eq "UnknownError") -and $Signature.SignerCertificate -and
(($Signature.SignerCertificate.Thumbprint -eq "4F8842037D878C1FCDC6FD1313B200449716C353") -or
($Signature.SignerCertificate.Thumbprint -eq "7DEFA3C6C2138C05AAA135FB8096332DEB9603E1"))
) -or $Signature.Status -eq "Valid" )
} catch { } finally { return $result }
}
}
}
filter ConvertTo-Module {
$oldFile = $_
if( ([IO.Path]::GetExtension($oldFile) -eq ".ps1") -and
[Regex]::Match( [IO.File]::ReadAllText($oldFile),
"^[^#]*Export-ModuleMember.*", "MultiLine").Success )
{
$fileName = [IO.Path]::ChangeExtension($oldFile, ".psm1")
Move-Item $oldFile $fileName -Force
Get-Item $fileName
} else { Get-Item $oldFile }
}
## Get-WebFile (aka wget for PowerShell)
function Get-WebFile {
#.Synopsis
# Downloads a file or page from the web
#.Description
# Creates an HttpWebRequest to download a web file
#.Parameter URL
# The URL of the file/page to download
#.Parameter FileName
# A Path to save the downloaded content.
# Defaults to the current directory and the name of the download.
# You may specify just a folder name to use the source name as the file name.
#.Parameter Passthru
# Rather than saving the downloaded content to a file, output it.
# This is for text documents like web pages and rss feeds, and allows you to avoid temporarily caching the text in a file.
#.Parameter Quiet
# Supresses the Write-Progress during download
#.Parameter UserAgent
# Text to include at the front of the UserAgent string
# Defaults to PoshCode/3.2 (where 3.2 is the version of the script)
#.Example
# Get-WebFile http://PoshCode.org/PoshCode.psm1
#
# Downloads the latest version of this file to the current directory
#.Example
# Get-WebFile http://PoshCode.org/PoshCode.psm1 ~\Documents\WindowsPowerShell\Modules\PoshCode\
#
# Downloads the latest version of this file to a PoshCode module directory...
#.Example
# $RssItems = @(([xml](Get-WebFile http://poshcode.org/api/ -passthru)).rss.channel.GetElementsByTagName("item"))
#
# Returns the most recent items from the PoshCode.org RSS feed
#.Notes
# History:
# v3.12 - Added full help
# v3.9 - Fixed and replaced the Set-DownloadFlag
# v3.7 - Removed the Set-DownloadFlag code because it was throwing on Windows 7:
# "Attempted to read or write protected memory."
# v3.6.6 Add UserAgent calculation and parameter
# v3.6.5 Add file-name guessing and cleanup
# v3.6 - Add -Passthru switch to output TEXT files
# v3.5 - Add -Quiet switch to turn off the progress reports ...
# v3.4 - Add progress report for files which don't report size
# v3.3 - Add progress report for files which report their size
# v3.2 - Use the pure Stream object because StreamWriter is based on TextWriter:
# it was messing up binary files, and making mistakes with extended characters in text
# v3.1 - Unwrap the filename when it has quotes around it
# v3 - rewritten completely using HttpWebRequest + HttpWebResponse to figure out the file name, if possible
# v2 - adds a ton of parsing to make the output pretty
# added measuring the scripts involved in the command, (uses Tokenizer)
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,Position=0)]
[string]$Url # = (Read-Host "The URL to download")
,
[string]$FileName
,
[switch]$Passthru,
[switch]$Quiet,
[string]$UserAgent = "PoshCode/$($PoshCode.ScriptVersion)"
)
Write-Verbose "Downloading '$url'"
$request = [System.Net.HttpWebRequest]::Create($url);
$request.UserAgent = $(
"{0} (PowerShell {1}; .NET CLR {2}; {3}; http://PoshCode.org)" -f $UserAgent,
$(if($Host.Version){$Host.Version}else{"1.0"}),
[Environment]::Version,
[Environment]::OSVersion.ToString().Replace("Microsoft Windows ", "Win")
)
if($request.Proxy -ne $null) {
$request.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
}
try {
$res = $request.GetResponse();
} catch [System.Net.WebException] {
Write-Error $_.Exception -Category ResourceUnavailable
return
}
if((Test-Path variable:res) -and $res.StatusCode -eq 200) {
if($fileName -and !(Split-Path $fileName)) {
$fileName = Join-Path (Convert-Path (Get-Location -PSProvider "FileSystem")) $fileName
}
elseif((!$Passthru -and !$fileName) -or ($fileName -and (Test-Path -PathType "Container" $fileName)))
{
[string]$fileName = ([regex]'(?i)filename=(.*)$').Match( $res.Headers["Content-Disposition"] ).Groups[1].Value
$fileName = $fileName.trim("\/""'")
$ofs = ""
$fileName = [Regex]::Replace($fileName, "[$([Regex]::Escape(""$([System.IO.Path]::GetInvalidPathChars())$([IO.Path]::AltDirectorySeparatorChar)$([IO.Path]::DirectorySeparatorChar)""))]", "_")
$ofs = " "
if(!$fileName) {
$fileName = $res.ResponseUri.Segments[-1]
$fileName = $fileName.trim("\/")
if(!$fileName) {
$fileName = Read-Host "Please provide a file name"
}
$fileName = $fileName.trim("\/")
if(!([IO.FileInfo]$fileName).Extension) {
$fileName = $fileName + "." + $res.ContentType.Split(";")[0].Split("/")[1]
}
}
$fileName = Join-Path (Convert-Path (Get-Location -PSProvider "FileSystem")) $fileName
}
if($Passthru) {
$encoding = [System.Text.Encoding]::GetEncoding( $res.CharacterSet )
[string]$output = ""
}
[int]$goal = $res.ContentLength
$reader = $res.GetResponseStream()
if($fileName) {
$writer = new-object System.IO.FileStream $fileName, "Create"
}
[byte[]]$buffer = new-object byte[] 4096
[int]$total = [int]$count = 0
do
{
$count = $reader.Read($buffer, 0, $buffer.Length);
if($fileName) {
$writer.Write($buffer, 0, $count);
}
if($Passthru){
$output += $encoding.GetString($buffer,0,$count)
} elseif(!$quiet) {
$total += $count
if($goal -gt 0) {
Write-Progress "Downloading $url" "Saving $total of $goal" -id 0 -percentComplete (($total/$goal)*100)
} else {
Write-Progress "Downloading $url" "Saving $total bytes..." -id 0
}
}
} while ($count -gt 0)
$reader.Close()
if($fileName) {
$writer.Flush()
$writer.Close()
}
if($Passthru){
$output
}
}
if(Test-Path variable:res) { $res.Close(); }
if($fileName) {
Set-DownloadFlag $fileName -PassThru
}
}
$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
function Set-DownloadFlag {
<#
.Synopsis
Sets the ZoneTransfer flag which marks a file as being downloaded from the internet.
.Description
Creates a Zone.Identifier alternate data stream (on NTFS file systems) and writes the ZoneTransfer marker
.Parameter Path
The file you wish to block
.Parameter Passthru
If set, outputs the FileInfo object
.Parameter ZoneId
THe Zone you want to mark the file with. Defaults to 4
#>
[CmdletBinding()]
PARAM (
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[string]
$Path
,
[Parameter(Position=1, Mandatory=$false)]
[ZoneIdentifier]$Zone = "Untrusted"
,
[Switch]$Passthru
)
PROCESS {
$FS = new-object PoshCodeNTFS.FileStreams($Path)
$null = $fs.add('Zone.Identifier')
$stream = $fs.Item('Zone.Identifier').open()
$sw = [System.IO.streamwriter]$stream
$Sw.writeline('[ZoneTransfer]')
$sw.writeline("ZoneID=$([Int]$zone)")
$sw.close()
$stream.close()
if($Passthru){ Get-ChildItem $Path }
}
}
function Remove-DownloadFlag {
<#
.Synopsis
Removes the ZoneTransfer flag which marks a file as being downloaded from the internet.
.Description
Deletes the Zone.Identifier alternate data stream (on NTFS file systems)
.Parameter Path
The file you wish to block
.Parameter Passthru
If set, outputs the FileInfo object
#>
[CmdletBinding()]
PARAM (
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[string]
$Path
,
[Switch]$Passthru
)
PROCESS {
Remove-Stream -Path $Path -Name 'Zone.Identifier'
if($Passthru){ Get-ChildItem $Path }
}
}
function Get-DownloadFlag {
<#
.Synopsis
Verify whether the ZoneTransfer flag is set (marking this file as one downloaded from the internet).
.Description
Reads the Zone.Identifier alternate data stream (on NTFS file systems)
.Parameter Path
The file you wish to check the ZoneTransfer flag on
#>
[CmdletBinding()]
PARAM (
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[string]
$Path
)
Process {
$FS = new-object PoshCodeNTFS.FileStreams($Path)
if(!$fs.Item('Zone.Identifier') ) {
Write-Warning "Zone.Identifier not set on $Path (no Download Flag). This is the equivalent of a 'Trusted' flag."
return
}
$reader = [System.IO.streamreader]$fs.Item('Zone.Identifier').open()
try {
do {
$line = $reader.ReadLine()
} until (!$line -OR $line -eq '[ZoneTransfer]')
$out = new-object PSObject
while($zone = $reader.ReadLine()) {
$zone = $zone -split "="
if($zone.Count -lt 2) { break }
Add-Member -in $out -Type NoteProperty -Name $zone[0] -value ([ZoneIdentifier]$zone[1])
}
$out
} finally {
$reader.close()
}
}
}
function Test-DownloadFlag {
<#
.Synopsis
Verify whether the ZoneTransfer flag is set (marking this file as one downloaded from the internet).
.Description
Reads the Zone.Identifier alternate data stream (on NTFS file systems)
.Parameter Path
The file you wish to check the ZoneTransfer flag on
#>
[CmdletBinding()]
PARAM (
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[string]
$Path
)
Process {
Get-ChildItem $Path | Select Name, @{N="Downloaded";E={ [bool]((new-object PoshCodeNTFS.FileStreams($_)).Item('Zone.Identifier')) } }, FullName, Length
}
}
function Normalize-StreamName {
PARAM($Path,$StreamName)
if(!$StreamName -and !(Test-Path $Path -EA 0)) {
$Path, $Segment, $StreamName = $Path -split ":"
if($StreamName -or (Test-Path ($Path,$Segment -join ":") -EA 0)) {
$Path = $Path,$Segment -join ":"
} else {
$StreamName = $Segment
}
}
return $Path,$StreamName
}
function Get-Stream {
<#
.Synopsis
Get the list of alternate NTFS Streams
.Description
Reads the named alternate data stream on NTFS file systems.
.Parameter Path
The file you wish to read from. You may include the stream name in the format:
C:\Path\File.extension:stream name
.Parameter Stream
The name of the stream you wish to read from. If you pass this as a separate parameter, you should NOT include it in the Path.
#>
[CmdletBinding()]
PARAM (
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[Alias("FullName")]
[string]
$Path
,
[Parameter(Position=1,Mandatory=$false)]
[Alias("Name")][string]$StreamName
,
[Parameter()]
[Switch]$Force
)
Process {
$Path,$Stream = Normalize-StreamName $Path $StreamName
Write-Verbose "Path: $Path"
Write-Verbose "Stream: $Stream"
ForEach($file in Get-ChildItem $Path) {
$FS = new-object PoshCodeNTFS.FileStreams($file)
Write-Verbose "File: $File"
if(!$Stream) {
$FS
} else {
$FS | Where { $_.StreamName -like $Stream } | Tee -Var Output
if($Force -and -not $Output) {
$FS.add($Stream) > $null
$FS.Item($Stream)
}
}
}
}
}
function Get-StreamContent {
<#
.Synopsis
Get the contents of a named NTFS Stream
.Description
Reads the named alternate data stream (on NTFS file systems)
.Parameter StreamInfo
A StreamInfo object for the stream you want to get the content of.
.Parameter Path
The file to read from. You may include the stream name in the format:
C:\Path\File.extension:stream name
.Parameter StreamName
The name of the stream you wish to read from. If you pass this as a separate parameter, you should NOT include it in the Path.
#>
[CmdletBinding(DefaultParameterSetName="ByStream")]
PARAM (
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="ByName")]
[Alias("FullName")][string]$Path
,
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="ByStream")]
[PoshCodeNTFS.StreamInfo]$StreamInfo
,
[Parameter(Position=1, Mandatory=$false, ParameterSetName="ByName")]
[Alias("Name")][string]$StreamName
)
Process {
switch($PSCmdlet.ParameterSetName) {
"ByName" {
Get-Stream $Path $StreamName | Get-StreamContent
}
"ByStream" {
$fileStream = $StreamInfo.open()
$reader = [System.IO.StreamReader]$fileStream
$reader.ReadToEnd()
$fileStream.close()
}
}
}
}
function Remove-Stream {
<#
.Synopsis
Remove a stream from a file (or, delete the file).
.Description
Deletes the named alternate data stream (on NTFS file systems)
.Parameter StreamInfo
A StreamInfo object for the stream you want to get the content of.
.Parameter Path
The file to delete from. You may include the stream name in the format:
"C:\Path\File.extension:stream name"
.Parameter StreamName
The name of the stream you wish to remove. If you pass this as a separate parameter, you should NOT include it in the Path.
#>
[CmdletBinding(DefaultParameterSetName="ByStream")]
PARAM (
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="ByName")]
[Alias("FullName")][string]$Path
,
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="ByStream")]
[PoshCodeNTFS.StreamInfo]$StreamInfo
,
[Parameter(Position=1, Mandatory=$false, ParameterSetName="ByName")]
[Alias("Name")][string]$StreamName
)
Process {
switch($PSCmdlet.ParameterSetName) {
"ByName" {
foreach($StreamInfo in Get-Stream $Path $StreamName) {
Write-Verbose $($StreamInfo |Out-String)
$StreamInfo.Delete() > $null
}
}
"ByStream" {
$StreamInfo.Delete() > $null
}
}
}
}
function Set-StreamContent {
<#
.Synopsis
Set the contents of a named NTFS Stream
.Description
Sets the content of the named alternate data stream (on NTFS file systems)
.Parameter StreamInfo
A StreamInfo object for the stream you want to set the content of.
.Parameter Path
The file to set content on. You may include the stream name in the format:
"C:\Path\File.extension:stream name"
.Parameter StreamName
The name of the stream you wish to set. If you pass this as a separate parameter, you should NOT include it in the Path.
#>
[CmdletBinding(DefaultParameterSetName="ByStream")]
PARAM (
[Parameter(Position=0, Mandatory=$true, ValueFromPipelineByPropertyName=$true, ParameterSetName="ByName")]
[Alias("FullName")][string]$Path
,
[Parameter(Position=0, Mandatory=$true, ValueFromPipeline=$true, ParameterSetName="ByStream")]
[PoshCodeNTFS.StreamInfo]$StreamInfo
,
[Parameter(Position=1, Mandatory=$false, ParameterSetName="ByName")]
[Alias("Name")][string]$StreamName
,
[Parameter(Position=2, Mandatory=$true)]
[String]$Value
)
Process {
switch($PSCmdlet.ParameterSetName) {
"ByName" {
Write-Verbose "Path: $Path"
Get-Stream $Path $StreamName -Force | Set-StreamContent -Value $Value
}
"ByStream" {
$writer =[System.IO.streamwriter] $StreamInfo.Open()
$writer.Write($value)
$writer.close()
}
}
}
}
Add-Type -TypeDefinition @'
public enum PoshCodeLanguage {
asp,
bash,
csharp,
posh,
vbnet,
xml,
text
}
'@
Add-Type -TypeDefinition @'
public enum ZoneIdentifier {
Trusted = 1,
Intranet = 2,
Internet = 3,
Untrusted = 4
}
'@
Add-Type -TypeDefinition @'
using System;
using System.IO;
using System.Collections;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
///<summary>
///Encapsulates access to alternative data streams of an NTFS file.
///Adapted from a C++ sample by Dino Esposito,
///http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnfiles/html/ntfs5.asp
///</summary>
namespace PoshCodeNTFS {
/// <summary>
/// Wraps the API functions, structures and constants.
/// </summary>
internal class Kernel32
{
public const char STREAM_SEP = ':';
public const int INVALID_HANDLE_VALUE = -1;
public const int MAX_PATH = 256;
[Flags()] public enum FileFlags : uint
{
WriteThrough = 0x80000000,
Overlapped = 0x40000000,
NoBuffering = 0x20000000,
RandomAccess = 0x10000000,
SequentialScan = 0x8000000,
DeleteOnClose = 0x4000000,
BackupSemantics = 0x2000000,
PosixSemantics = 0x1000000,
OpenReparsePoint = 0x200000,
OpenNoRecall = 0x100000
}
[Flags()] public enum FileAccessAPI : uint
{
GENERIC_READ = 0x80000000,
GENERIC_WRITE = 0x40000000
}
/// <summary>
/// Provides a mapping between a System.IO.FileAccess value and a FileAccessAPI value.
/// </summary>
/// <param name="Access">The <see cref="System.IO.FileAccess"/> value to map.</param>
/// <returns>The <see cref="FileAccessAPI"/> value.</returns>
public static FileAccessAPI Access2API(FileAccess Access)
{
FileAccessAPI lRet = 0;
if ((Access & FileAccess.Read)==FileAccess.Read) lRet |= FileAccessAPI.GENERIC_READ;
if ((Access & FileAccess.Write)==FileAccess.Write) lRet |= FileAccessAPI.GENERIC_WRITE;
return lRet;
}
[StructLayout(LayoutKind.Sequential)] public struct LARGE_INTEGER
{
public int Low;
public int High;
public long ToInt64()
{
return (long)High * 4294967296 + (long)Low;
}
}
[StructLayout(LayoutKind.Sequential)] public struct WIN32_STREAM_ID
{
public int dwStreamID;
public int dwStreamAttributes;
public LARGE_INTEGER Length;
public int dwStreamNameLength;
}
[DllImport("kernel32")] public static extern SafeFileHandle CreateFile(string Name, FileAccessAPI Access, FileShare Share, int Security, FileMode Creation, FileFlags Flags, int Template);
[DllImport("kernel32")] public static extern bool DeleteFile(string Name);
[DllImport("kernel32")] public static extern bool CloseHandle(SafeFileHandle hObject);
[DllImport("kernel32")] public static extern bool BackupRead(SafeFileHandle hFile, IntPtr pBuffer, int lBytes, ref int lRead, bool bAbort, bool bSecurity, ref int Context);
[DllImport("kernel32")] public static extern bool BackupRead(SafeFileHandle hFile, ref WIN32_STREAM_ID pBuffer, int lBytes, ref int lRead, bool bAbort, bool bSecurity, ref int Context);
[DllImport("kernel32")] public static extern bool BackupSeek(SafeFileHandle hFile, int dwLowBytesToSeek, int dwHighBytesToSeek, ref int dwLow, ref int dwHigh, ref int Context);
}
/// <summary>
/// Encapsulates a single alternative data stream for a file.
/// </summary>
public class StreamInfo
{
private FileStreams _parent;
private string _name;
private long _length;
internal StreamInfo(FileStreams Parent, string Name, long Length)
{
_parent = Parent;
_name = Name;
_length = Length;
}
/// <summary>
/// The name of the file.
/// </summary>
public string FileName
{
get { return System.IO.Path.GetFileName(_parent.FileName); }