-
Notifications
You must be signed in to change notification settings - Fork 0
/
script_validator.ps1
98 lines (77 loc) · 2.6 KB
/
script_validator.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
$OutputEncoding = New-Object -typename System.Text.UTF8Encoding
Write-Host "`nPS Script Validator and Encoding checker..."
Write-Host "`n-----------------------------------------------------"
function Get-FileName($initialDirectory)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") |
Out-Null
$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "All files (*.*)| *.*"
$OpenFileDialog.ShowDialog() | Out-Null
$OpenFileDialog.filename
}
$ScriptPath = Get-FileName
function Get-Encoding
{
param([Parameter(ValueFromPipeline=$True)] $filename)
begin {}
process
{
$reader = [System.IO.StreamReader]::new($filename, [System.Text.Encoding]::default,$true)
$peek = $reader.Peek()
$encoding = $reader.currentencoding
$reader.close()
[pscustomobject]@{
Name=split-path $filename -leaf
BodyName=$encoding.BodyName
EncodingName=$encoding.EncodingName
}
}
}
function Test-PSScript
{
param(
[Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias('PSPath','FullName')]
[System.String[]] $FilePath,
[Switch]$IncludeSummaryReport
)
begin
{
$total=$fails=0
}
process
{
$FilePath | Foreach-Object {
#check whether it is a file or not
if(Test-Path -Path $_ -PathType Leaf)
{
$Path = Convert-Path –Path $_
$Errors = $null
$Content = Get-Content -Path $path
$Tokens = [System.Management.Automation.PsParser]::Tokenize($Content,[ref]$Errors)
if($Errors)
{
$fails+=1
$Errors | Foreach-Object {
$_.Token | Add-Member -MemberType NoteProperty -Name Path -Value $Path -PassThru | `
Add-Member –MemberType NoteProperty -Name ErrorMessage -Value $_.Message -PassThru
}
}
$total+=1
}
}
}
end
{
if($IncludeSummaryReport)
{
Write-Host "`n$total script(s) processed, $fails script(s) contain syntax errors."
Write-Host "`n-----------------------------------------------------"
}
}
}
Test-PSScript -PSPAth $ScriptPath -IncludeSummaryReport
Get-Encoding $ScriptPath