-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathCommunary.FileExtensions.psm1
More file actions
923 lines (831 loc) · 32.3 KB
/
Communary.FileExtensions.psm1
File metadata and controls
923 lines (831 loc) · 32.3 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
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
# Communary.FileExtensions
# 2015 Øyvind Kallstad (@okallstad)
Add-Type -Path $PSScriptRoot\FileExtensions.cs
function Invoke-FastFind {
<#
.SYNOPSIS
Search for files and folders.
.DESCRIPTION
This function uses WIN32 API to perform faster searching for files and folders. It also supports large paths.
.EXAMPLE
Invoke-FastFind
Will list all files and folders in the current directory.
.EXAMPLE
Invoke-FastFind c:\
Will list all files and folders in c:\
.EXAMPLE
Invoke-FastFind c:\ prog*
Will list all files and folders in c:\ that starts with 'prog'.
.EXAMPLE
Invoke-FastFind c:\ -Directory
Will list all directories in c:\
.EXAMPLE
Invoke-FastFind c:\ -Directory -Hidden
Will list all hidden directories in c:\
.EXAMPLE
Invoke-FastFind c:\ -System -Hidden -AttributeFilterMode Exclude
Will list all files and folders in c:\ that don't have the System and Hidden attributes set.
.EXAMPLE
Invoke-FastFind c:\ -Hidden -System -Archive -AttributeFilterMode Strict
Will list all files and folders in c:\ that only have the Hidden, System and Archive attributes set.
.NOTES
Author: Øyvind Kallstad
Date: 13.11.2015
Version: 1.0
.LINK
https://communary.wordpress.com/
https://github.com/gravejester/Communary.FileExtensions
#>
[CmdletBinding()]
param (
# Path where search starts from. The default value is the current directory.
[Parameter(Position = 1)]
[ValidateNotNullOrEmpty()]
[string[]] $Path = ((Get-Location).Path),
# Search filter. Accepts wildcards; * and ?. The default value is '*'.
[Parameter(Position = 2)]
[string] $Filter = '*',
[Parameter()]
[Alias('f')]
[switch] $File,
[Parameter()]
[Alias('d')]
[switch] $Directory,
[Parameter()]
[switch] $Hidden,
[Parameter()]
[switch] $System,
[Parameter()]
[switch] $ReadOnly,
[Parameter()]
[switch] $Compressed,
[Parameter()]
[switch] $Archive,
[Parameter()]
[switch] $ReparsePoint,
# Choose the filter mode for attribute filtering. Valid choices are 'Include', 'Exclude' and 'Strict'. Default is 'Include'.
[Parameter()]
[ValidateSet('Include','Exclude','Strict')]
[string] $AttributeFilterMode = 'Include',
# Perform recursive search.
[Parameter()]
[Alias('r')]
[switch] $Recurse,
# Depth of recursive search. Default is null (unlimited recursion).
[Parameter()]
[nullable[int]] $Depth = $null,
# Use a larger buffer for the search, which *can* increase performance. Not supported for operating systems older than Windows Server 2008 R2 and Windows 7.
[Parameter()]
[switch] $LargeFetch
)
if ($PSBoundParameters['File'] -and $PSBoundParameters['Directory']) {
$File = $false
$Directory = $false
}
foreach ($thisPath in $Path) {
#if (Test-Path -Path $thisPath) {
# adds support for relative paths
#$resolvedPath = (Resolve-Path -Path $thisPath).Path
#$resolvedPath = $resolvedPath.Replace('Microsoft.PowerShell.Core\FileSystem::','')
$resolvedPath = $thisPath
# handle a quirk where \ at the end of a non-UNC, non-root path failes
if (-not ($resolvedPath.ToString().StartsWith('\\'))) {
if ($resolvedPath.ToString().EndsWith('\')) {
if (-not($resolvedPath -eq ([System.IO.Path]::GetPathRoot($resolvedPath)))) {
$resolvedPath = $resolvedPath.ToString().TrimEnd('\')
}
}
}
# call FastFind to perform search
[Communary.FileExtensions]::FastFind($resolvedPath, $Filter, $File, $Directory, $Recurse, $Depth, $true, $true, $LargeFetch, $Hidden, $System, $ReadOnly, $Compressed, $Archive, $ReparsePoint, $AttributeFilterMode)
#}
#else {
# Write-Warning "$thisPath - Invalid path"
#}
}
}
function Get-DirectoryInfo {
<#
.SYNOPSIS
Get general information about specified directory.
.DESCRIPTION
Get information about number of files and folders and total size for a given directory.
This function supports long paths, both local and UNC.
Note that the SizeOnDisk value is only an approximation!
.EXAMPLE
Get-DirectoryInfo
Get directory information about current directory.
.EXAMPLE
Get-DirectoryInfo c:\windows
Get directory information about the c:\windows directory
.NOTES
Author: Øyvind Kallstad
Date: 13.11.2015
Version: 1.0
.LINK
https://communary.wordpress.com/
https://github.com/gravejester/Communary.FileExtensions
#>
[CmdletBinding()]
param (
[Parameter(Position = 1)]
[ValidateNotNullOrEmpty()]
[string[]] $Path = ((Get-Location).Path)
)
foreach ($thisPath in $Path) {
$sectorSize = [Communary.FileExtensions]::GetSectorSize($thisPath)
$pathContents = [Communary.FileExtensions]::FastFind($thisPath, '*', $false, $false, $true, $null, $true, $true, $false, $false, $false, $false, $false, $false, $false, 'Include')
$numberOfFolders = ($pathContents | Where-Object {$_.Attributes.HasFlag([System.IO.FileAttributes]::Directory)}).Count
$numberOfFiles = $pathContents.count - $numberOfFolders
[long]$totalSize = 0
foreach ($item in $pathContents) {
$totalSize = $totalSize + $item.FileSize
}
[long]$sizeOnDisk = (($totalSize + $sectorSize - 1) / $sectorSize) * $sectorSize
Write-Output (,([PSCustomObject] @{
Path = $thisPath
NumberOfDirectories = $numberOfFolders
NumberOfFiles = $numberOfFiles
TotalSize = $totalSize
SizeOnDisk = $sizeOnDisk
}))
}
}
function Remove-File {
<#
.SYNOPSIS
Delete file(s).
.DESCRIPTION
Delete one or more files. This function supports long paths, both local and UNC.
.EXAMPLE
Remove-File c:\temp\tempfile.txt
Will remove the file c:\temp\tempfile.txt after prompting you for confirmation.
.EXAMPLE
c:\temp\tempfile.txt | Remove-File
Will remove the file c:\temp\tempfile.txt after prompting you for confirmation.
.EXAMPLE
Remove-File c:\temp\tempfile.txt -WhatIf
Will give you information about what the function would perform if used without the -WhatIf parameter.
.EXAMPLE
Remove-File c:\temp\tempfile.txt -Force
Will remove the file c:\temp\tempfile.txt without prompting you for confirmation.
.NOTES
Author: Øyvind Kallstad
Date: 13.11.2015
Version: 1.1
Update 11.12.2015: Will now also delete Read-Only files.
.LINK
https://communary.wordpress.com/
https://github.com/gravejester/Communary.FileExtensions
#>
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='High')]
param (
[Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[ValidateNotNullOrEmpty()]
[string[]] $Path,
[Parameter()]
[switch] $Force
)
PROCESS {
foreach ($thisPath in $Path) {
if ($Force -or $PSCmdlet.ShouldProcess($thisPath,'Delete')) {
try {
if ((Get-FileAttribute -Path $thisPath) -like '*ReadOnly*') {
Set-FileAttribute -Path $thisPath -Normal
}
[Communary.FileExtensions]::DeleteFile($thisPath)
}
catch {
Write-Warning "Failed to remove $($thisPath): $($_.Exception.Message)"
}
}
}
}
}
function Remove-Directory {
<#
.SYNOPSIS
Delete folder(s).
.DESCRIPTION
Delete one or more directory. This function supports long paths, both local and UNC.
Function will fail if directory is not empty.
.EXAMPLE
Remove-Directory c:\temp\tempfolder
Will remove the directory c:\temp\tempfolder after prompting you for confirmation.
.EXAMPLE
c:\temp\tempfolder | Remove-Directory
Will remove the directory c:\temp\tempfolder after prompting you for confirmation.
.EXAMPLE
Remove-Directory c:\temp\tempfolder -WhatIf
Will give you information about what the function would perform if used without the -WhatIf parameter.
.EXAMPLE
Remove-Directory c:\temp\tempfolder -Force
Will remove the directory c:\temp\tempfolder without prompting you for confirmation.
.NOTES
Author: Øyvind Kallstad
Date: 14.11.2015
Version: 1.0
.LINK
https://communary.wordpress.com/
https://github.com/gravejester/Communary.FileExtensions
#>
[CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='High')]
param (
[Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
[ValidateNotNullOrEmpty()]
[string[]] $Path,
[Parameter()]
[switch] $Force
)
PROCESS {
foreach ($thisPath in $Path) {
if ($Force -or $PSCmdlet.ShouldProcess($thisPath,'Delete')) {
try {
[Communary.FileExtensions]::DeleteDirectory($thisPath)
}
catch {
Write-Warning "Failed to remove $($thisPath): $($_.Exception.Message)"
}
}
}
}
}
#function Remove-DirectoryRecurse {
# [CmdletBinding()]
# param (
# [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
# [ValidateNotNullOrEmpty()]
# [string[]] $Path
# )
#
# PROCESS {
# foreach ($thisPath in $Path) {
# #remove all files
# Invoke-FastFind -Path $thisPath -Filter '*' -File -Recurse | Remove-File -Force
#
# # remove all folders
# $folders = New-Object System.Collections.ArrayList
# try {
# $folders.AddRange((Invoke-FastFind -Path $thisPath -Filter '*' -Directory -Recurse))
# $folders.Reverse()
# $folders | Select-Object -ExpandProperty Path | Remove-Directory -Force
# }
# catch {}
# # remove the top folder
# Remove-Directory -Path $thisPath -Force
# }
# }
#}
function New-Tempfile {
<#
.SYNOPSIS
Create a new temporary file.
.DESCRIPTION
This function creates a uniquely named, zero-byte temporary file with a .TMP file extension.
The temporary file is created within the user’s temporary folder and the FileInfo object of that file is returned.
.NOTES
Author: Øyvind Kallstad
Date: 13.11.2015
Version: 1.0
.LINK
https://communary.wordpress.com/
https://github.com/gravejester/Communary.FileExtensions
#>
try {
$tmpFile = [System.IO.Path]::GetTempFileName()
$tmpFileObject = Get-Item -Path $tmpFile
Write-Output $tmpFileObject
}
catch {
Write-Warning $_.Exception.Message
}
}
function Get-TempFolder {
<#
.SYNOPSIS
Returns the current user's temporary folder.
.DESCRIPTION
Returns the current user's temporary folder.
.NOTES
Author: Øyvind Kallstad
Date: 13.11.2015
Version: 1.0
.LINK
https://communary.wordpress.com/
https://github.com/gravejester/Communary.FileExtensions
#>
$tmpFolder = [System.IO.Path]::GetTempPath()
$tmpFolderObject = Get-Item -Path $tmpFolder
Write-Output $tmpFolderObject
}
function Get-RandomFileName {
<#
.SYNOPSIS
Returns a random folder name or file name.
.DESCRIPTION
Returns a cryptographically strong, random string that can be used as either a folder name or a file name.
.NOTES
Author: Øyvind Kallstad
Date: 13.11.2015
Version: 1.0
.LINK
https://communary.wordpress.com/
https://github.com/gravejester/Communary.FileExtensions
#>
[System.IO.Path]::GetRandomFileName()
}
function Resolve-PathEx {
<#
.SYNOPSIS
Resolve-Path extended to also work with files that don't exist.
.DESCRIPTION
You can use Resolve-PathEx when you want to handle both filenames and paths in a single parameter in your functions.
The function returns an object, and includes the resolved path as well as a boolean indicating whether the file
exists or not. Wildcards are supported for both path and filename.
.EXAMPLE
Resolve-Path *.ps1
Will resolve full path of all files in the current directory with the ps1 file extension.
.EXAMPLE
Resolve-PathEx c:\program*\windows*\w*.exe
Will resolve full path of all exe files beginning with w in any folders of the root of C: that starts with 'progra',
and all subfolders of these that start with 'windows'.
.EXAMPLE
Resolve-Path
Will resolve the current path.
.EXAMPLE
Resolve-Path nosuchfile.txt
Will resolve the full path of the file, even though it doesn't exist.
.LINK
https://communary.wordpress.com/
https://github.com/gravejester/Communary.FileExtensions
.NOTES
Author: Øyvind Kallstad
Date: 13.11.2014
Version: 1.0
#>
[CmdletBinding()]
param (
[Parameter(Position = 0, ValueFromPipeline, ValueFromPipelinebyPropertyName)]
[string[]] $Path = '.\'
)
PROCESS{
foreach ($thisPath in $Path) {
try {
# first try to resolve using the whole path
[array]$resolvedPath += (Resolve-Path -Path $thisPath -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Path)
# if that didn't work, split to get the path only
if ([string]::IsNullOrEmpty($resolvedPath)) {
$pathOnly = Split-Path $thisPath
# if no path returned, add current directory as path
if ([string]::IsNullOrEmpty($pathOnly)) {
$pathOnly = '.\'
}
# try to resolve again using only the path
$pathOnlyResolve = (Resolve-Path -Path $pathOnly -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Path)
# if successfull
if (-not([string]::IsNullOrEmpty($pathOnlyResolve))) {
# add the path and the filename back together
foreach ($p in $pathOnlyResolve) {
$pathAndFile = Join-Path -Path $p -ChildPath (Split-Path -Path $thisPath -Leaf)
$exists = Test-Path $pathAndFile
Write-Output (,([PSCustomObject] [Ordered] @{
Path = $pathAndFile
Exists = $exists
}))
}
}
# if we still are unable to resolve, the path most likely don't exist
else {
Write-Warning "Unable to resolve $pathOnly"
}
}
else {
foreach ($item in $resolvedPath) {
$exists = Test-Path $item
Write-Output (,([PSCustomObject] [Ordered] @{
Path = $item
Exists = $exists
}))
}
}
}
catch {
Write-Warning $_.Exception.Message
}
}
}
}
function Invoke-Touch {
<#
.SYNOPSIS
PowerShell inplementation of the Unix/Linux utility called touch.
.DESCRIPTION
Touch let's you update the access date and / or modification date of a file. If the file don't exist, an empty file will be created
unless you use the DoNotCreateNewFile parameter. This implementation have the original parameter names added as
aliases, so if you are familiar with the original touch utility it should be easy to use this one.
.EXAMPLE
Invoke-Touch newfile
Will create a new empty file called 'newfile' in the current folder.
.EXAMPLE
Invoke-Touch newfile3 -DateTime '10.10.2014'
Will create a new empty file called 'newfile3' with the provided date.
.EXAMPLE
Invoke-Touch newfile -r newfile3
Will update the timestamp of 'newfile' using 'newfile3' as a reference.
.LINK
https://gist.github.com/gravejester/f4934a5ce16c652d11d3
.NOTES
Author: Øyvind Kallstad
Date: 13.11.2014
Version: 1.0
#>
[CmdletBinding(ConfirmImpact = 'Low',SupportsShouldProcess = $true, DefaultParameterSetName = 'UserDateTime')]
param (
# Filename and/or path.
[Parameter(Position = 0, ValueFromPipeline, ValueFromPipelinebyPropertyName)]
[string[]] $Path,
# File to use as a timestamp reference.
[Parameter(ParameterSetName = 'ReferenceDateTime')]
[Alias('r')]
[string] $Reference,
# Timestamp offset in seconds.
[Parameter()]
[Alias('B','F')]
[int] $OffsetSeconds = 0,
# Used to override the timestamp. If omitted the current date and time will be used.
[Parameter(ParameterSetName = 'UserDateTime')]
[Alias('t','d')]
[string] $DateTime,
# Update Last Access Time.
[Parameter()]
[Alias('a')]
[switch] $AccessTime,
# Update Last Write Time.
[Parameter()]
[Alias('m','w')]
[switch] $WriteTime,
# Switch to override the basic functionality of creating a new file if it don't exist already.
[Parameter()]
[Alias('c')]
[switch] $DoNotCreateNewFile,
[Parameter()]
[switch] $PassThru
)
BEGIN {
try {
# use timestamp from a reference file
if (-not([string]::IsNullOrEmpty($Reference))) {
if (Test-Path $Reference) {
$referenceFile = Get-ChildItem -Path $Reference
$newLastAccessTime = ($referenceFile.LastAccessTime).AddSeconds($OffsetSeconds)
$newLastWriteTime = ($referenceFile.LastWriteTime).AddSeconds($OffsetSeconds)
Write-Verbose "Using timestamp from $Reference"
}
else {
Write-Warning "$Reference not found!"
}
}
# use timestamp from user input
elseif (-not([string]::IsNullOrEmpty($DateTime))) {
$userDateTime = [DateTime]::Parse($DateTime,[CultureInfo]::CurrentCulture,[System.Globalization.DateTimeStyles]::NoCurrentDateDefault)
Write-Verbose "Using timestamp from user input: $DateTime (Parsed: $($userDateTime))"
}
# use timestamp from current date/time
else {
$currentDateTime = (Get-Date).AddSeconds($OffsetSeconds)
$newLastAccessTime = $currentDateTime
$newLastWriteTime = $currentDateTime
Write-Verbose "Using timestamp from current date/time: $currentDateTime"
}
}
catch {
Write-Warning $_.Exception.Message
}
}
PROCESS {
foreach ($thisPath in $Path) {
try {
$thisPathResolved = Resolve-PathEx -Path $thisPath
foreach ($p in $thisPathResolved.Path) {
Write-Verbose "Resolved path: $p"
# if file is not found, and it's ok to create a new file, create it!
if (-not(Test-Path $p)) {
if ($DoNotCreateNewFile) {
Write-Verbose "$p not created"
return
}
else {
if ($PSCmdlet.ShouldProcess($p, 'Create File')) {
$null = New-Item -path $p -ItemType 'File' -ErrorAction 'Stop'
}
}
}
# get fileinfo object
$fileObject = Get-ChildItem $p -ErrorAction SilentlyContinue
if (-not([string]::IsNullOrEmpty($fileObject))) {
# handle date & time if datetime parameter is used
if (-not([string]::IsNullOrEmpty($DateTime))) {
# if parsed datetime object contains time
if ([bool]$userDateTime.TimeOfDay.Ticks) {
Write-Verbose 'Found time in datetime'
$userTime = $userDateTime.ToLongTimeString()
}
# else, get time from file
else {
Write-Verbose 'Did not find time in datetime - using time from file'
$userTime = $fileObject.LastAccessTime.ToLongTimeString()
}
# if parsed datetime object contains date
if ([bool]$userDateTime.Date.Ticks) {
Write-Verbose 'Found date in datetime'
$userDate = $userDateTime.ToShortDateString()
}
# else, get date from file
else {
Write-Verbose 'Did not find date in datetime - using date from file'
$userDate = $fileObject.LastAccessTime.ToShortDateString()
}
# parse the new datetime
$parsedNewDateTime = [datetime]::Parse("$userDate $userTime")
# add offset and save to the appropriate variables
$newLastAccessTime = $parsedNewDateTime.AddSeconds($OffsetSeconds)
$newLastWriteTime = $parsedNewDateTime.AddSeconds($OffsetSeconds)
}
}
if ($PSCmdlet.ShouldProcess($p, 'Update Timestamp')) {
# if neither -AccessTime nor -WriteTime is used, update both Last Access Time and Last Write Time
if ((-not($AccessTime)) -and (-not($WriteTime))) {
$fileObject.LastAccessTime = $newLastAccessTime
$fileObject.LastWriteTime = $newLastWriteTime
}
else {
if ($AccessTime) { $fileObject.LastAccessTime = $newLastAccessTime }
if ($WriteTime) { $fileObject.LastWriteTime = $newLastWriteTime }
}
}
}
if ($PassThru) {
Write-Output (Get-ChildItem $p)
}
}
catch {
Write-Warning $_.Exception.Message
}
}
}
}
function Set-FileAttribute {
<#
.SYNOPSIS
Set file attributes.
.DESCRIPTION
This function lets you set file attributes for file(s) or folder(s). Long paths are supported.
.NOTES
Author: Øyvind Kallstad
Date: 13.11.2015
Version: 1.0
.LINK
https://communary.wordpress.com/
https://github.com/gravejester/Communary.FileExtensions
#>
[CmdletBinding(DefaultParameterSetName = 'default')]
param (
[Parameter(Position = 1, ValueFromPipeline = $true, ValueFromPipelinebyPropertyname = $true)]
[ValidateNotNullOrEmpty()]
[string[]] $Path,
[Parameter(ParameterSetName = 'default')]
[switch] $Archive,
[Parameter(ParameterSetName = 'default')]
[switch] $Hidden,
[Parameter(ParameterSetName = 'normal')]
[switch] $Normal,
[Parameter(ParameterSetName = 'default')]
[switch] $ReadOnly,
[Parameter(ParameterSetName = 'default')]
[switch] $System
)
PROCESS {
foreach ($thisPath in $Path) {
if ($Normal) {
$attributes = [System.IO.FileAttributes]::Normal
}
else {
$attributesToAdd = @()
if ($Archive) {$attributesToAdd += [System.IO.FileAttributes]::Archive}
if ($Hidden) {$attributesToAdd += [System.IO.FileAttributes]::Hidden}
if ($ReadOnly) {$attributesToAdd += [System.IO.FileAttributes]::ReadOnly}
if ($System) {$attributesToAdd += [System.IO.FileAttributes]::System}
foreach ($thisAttribute in $attributesToAdd) {
$attributes = $attributes -bor $thisAttribute
}
}
try {
[Communary.FileExtensions]::AddFileAttributes($thisPath, $attributes)
}
catch {
Write-Warning "Failed to set attributes for $($thisPath): $($_.Exception.Message)"
}
}
}
}
function Get-FileAttribute {
<#
.SYNOPSIS
Get file attributes.
.DESCRIPTION
This function lets you get file attributes for file(s) or folder(s). Long paths are supported.
.NOTES
Author: Øyvind Kallstad
Date: 13.11.2015
Version: 1.0
.LINK
https://communary.wordpress.com/
https://github.com/gravejester/Communary.FileExtensions
#>
[CmdletBinding()]
param (
[Parameter(Position = 1, ValueFromPipeline = $true, ValueFromPipelinebyPropertyname = $true)]
[ValidateNotNullOrEmpty()]
[string[]] $Path
)
PROCESS {
foreach ($thisPath in $Path) {
try {
[System.IO.FileAttributes]$attributes = [Communary.FileExtensions]::GetFileAttributes($thisPath)
Write-Output $attributes
}
catch {
Write-Warning "Failed to get file attributes for $($thisPath): $($_.Exception.Message)"
}
}
}
}
function ConvertTo-UNCPath {
<#
.SYNOPSIS
Convert a path to UNC path
.DESCRIPTION
Convert a path to UNC path
.NOTES
Author: Øyvind Kallstad
Date: 26.10.2015
Version: 1.0
.INPUTS
System.String
.OUTPUTS
System.String
.LINK
https://communary.wordpress.com/
https://github.com/gravejester/Communary.FileExtensions
#>
[CmdletBinding()]
param (
[Parameter(Position = 2, ValueFromPipeline, ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[string] $Path,
[Parameter(Position = 1)]
[ValidateNotNullOrEmpty()]
[string] $ComputerName
)
$pathRoot = [System.IO.Path]::GetPathRoot($Path)
Write-Output ("\\$($ComputerName)$(($Path).Replace($pathRoot, "\$($Path[0])$\"))")
}
function Get-FileOwner {
<#
.SYNOPSIS
Get the owner of a file or a folder.
.DESCRIPTION
Get the owner of a file or a folder.. Supports large paths.
.NOTES
Author: Øyvind Kallstad
Date: 15.11.2015
Version: 1.0
.LINK
https://communary.wordpress.com/
https://github.com/gravejester/Communary.FileExtensions
#>
[CmdletBinding()]
param (
[Parameter(Position = 1, ValueFromPipeline = $true, ValueFromPipelinebyPropertyname = $true)]
[ValidateNotNullOrEmpty()]
[string[]] $Path
)
PROCESS {
foreach ($thisPath in $Path) {
try {
$fileOwner = [Communary.FileExtensions]::GetFileOwner($thisPath)
Write-Output $fileOwner
}
catch {
Write-Warning "Failed to get file owner for $($thisPath): $($_.Exception.Message)"
}
}
}
}
function Test-Exist {
<#
.SYNOPSIS
Test if a file or folder exist.
.DESCRIPTION
Test if a file or folder exist. Supports large paths.
.NOTES
Author: Øyvind Kallstad
Date: 15.11.2015
Version: 1.0
.LINK
https://communary.wordpress.com/
https://github.com/gravejester/Communary.FileExtensions
#>
[CmdletBinding()]
param (
[Parameter(Position = 1, ValueFromPipeline = $true, ValueFromPipelinebyPropertyname = $true)]
[string[]] $Path
)
PROCESS {
foreach ($thisPath in $Path) {
if ($thisPath) {
$pathSplit = $thisPath.Split('\', [System.StringSplitOptions]::RemoveEmptyEntries)
$filter = $pathSplit[-1]
$searchPath = $pathSplit[0..($pathSplit.Count - 2)] -join '\'
if ([bool](Invoke-FastFind -Path $searchPath -Filter $filter)) {
Write-Output $true
}
else {
Write-Output $false
}
}
else {
Write-Output $false
}
}
}
}
function Get-LastLine {
<#
.SYNOPSIS
Reads the last lines of a file.
.DESCRIPTION
Reads the last lines of a file.
.EXAMPLE
Get-LastLines -Path $pathToFile -Lines 1
Get the last line of the file.
.EXAMPLE
Get-LastLines -Path $pathToFile -Lines 10
Get the 10 last lines of the file.
.EXAMPLE
$pathToFile | last 1
Get the last line of the file (using the alias 'last').
.NOTES
Author: Øyvind Kallstad
Date: 15.11.2015
Version: 1.0
.LINK
https://communary.wordpress.com/
https://github.com/gravejester/Communary.FileExtensions
#>
[CmdletBinding()]
param (
[Parameter(Position = 2, ValueFromPipeline = $true, ValueFromPipelinebyPropertyname = $true)]
[ValidateNotNullOrEmpty()]
[string] $Path,
[Parameter(Position = 1)]
[ValidateRange(1,[int]::MaxValue)]
[int] $Lines = 1
)
Write-Output ([Communary.FileExtensions]::ReadLastLines($Path, $Lines))
}
function Test-FolderIsEmpty {
<#
.SYNOPSIS
Test if a folder is empty or not.
.DESCRIPTION
Test if a folder is empty or not.
.NOTES
Author: Øyvind Kallstad
Date: 16.11.2015
Version: 1.0
.LINK
https://communary.wordpress.com/
https://github.com/gravejester/Communary.FileExtensions
#>
[CmdletBinding()]
param (
[Parameter(Position = 1, ValueFromPipeline = $true, ValueFromPipelinebyPropertyname = $true)]
[ValidateNotNullOrEmpty()]
[string] $Path
)
PROCESS {
foreach ($thisPath in $Path) {
if ([bool](Invoke-FastFind -Path $thisPath -Recurse)) {
Write-Output $false
}
else {
Write-Output $true
}
}
}
}
Set-Alias -Name 'touch' -Value 'Invoke-Touch' -Force
Set-Alias -Name 'ff' -Value 'Invoke-FastFind' -Force
Set-Alias -Name 'du' -Value 'Get-DirectoryInfo' -Force
Set-Alias -Name 'last' -Value 'Get-LastLines' -Force