-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsysadmin-tools.psm1
257 lines (220 loc) · 8.4 KB
/
sysadmin-tools.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
# Function Alias Definitions
Set-Alias -name dir-size -value Get-Directory-Size
Set-Alias -name p -value Ping-Host
Set-Alias -name logged-in -value Get-Logged-In-User
Set-Alias -name my-ip -value Get-My-IP-Address
Set-Alias -name welcome -value Get-Welcome-Message
Set-Alias -name password -value New-Random-Password
## Input your name for the welcome script
$myName = ""
## Default window title for your terminal
$default_window_title = "PowerShell "+$host.Version
# Customizes the appearance of the PowerShell Prompt. Adjust the variables below to change how the path is displayed, the prompt symbol, and the colors.
function prompt {
# BEGIN CUSTOMIZATION #
$CustomizePrompt = 1 # Set this value to '0' if you do not want the prompt to be customized.
$CurrentFolderOnly = 0 # Set to "0" to print full path. Set to "1" to print current folder only.
$ReplaceHomeDir = 1 # Set to "1" to replace the user's home directory with a symbol.
$HomeDirSymbol = "~" # Choose the symbol to represent the user's home directory
$PathColor = "DarkGray" # Choose the color for the path.
$PromptSymbol = ">" # Choose the symbol that follows the path.
$PromptSymbolColor = "Green" # Choose the color of this symbol.
# END CUSTOMIZATION #
# Return null if we do not want the prompt to be modified.
if(! $CustomizePrompt){
return $Null
}
# Initialize PromptPath
$PromptPath = "$PWD"
# Replaces the user's home directory path with a symbol, if set above
if($ReplaceHomeDir){
if($PromptPath -like "$HOME*"){
$PromptPath = $PromptPath -replace [regex]::Escape($HOME), $HomeDirSymbol
}
}
# Displays only the current folder from the path, if set above
if($CurrentFolderOnly){
$PromptPath = "$PromptPath".Split('\')[-1]
}
# Write the prompt path
Write-Host $PromptPath -NoNewline -ForegroundColor $PathColor
# Write the prompt symbol
Write-Host $PromptSymbol -NoNewline -ForegroundColor $PromptSymbolColor
return " "
}
## Convert file sizes into human readable format
function Format-FileSize {
param (
[float]$size
)
$units = "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"
$index = 0
while ($size -ge 1024 -and $index -lt $units.Length) {
$size /= 1024
$index++
}
return "{0:N2} {1}" -f $size, $units[$index]
}
## dir-size [*path]
## Calculate the size of a directory, including all sub-files and folders.
function Get-Directory-Size {
param ([string]$path,[switch]$bytes,[switch]$NoRecurse)
if($NoRecurse){
$size = (Get-ChildItem -Force $path | Measure-Object -Property Length -Sum).Sum
} else {
$size = (Get-ChildItem -Recurse -Force $path | Measure-Object -Property Length -Sum).Sum
}
if($bytes){
Write-Host $size
} else {
Write-Host (Format-FileSize $size)
}
}
## Function: p [*hostname] [count]
## Replacement for ping. An optional count parameter can be supplied. If none is given, the ping will run indefinetly.
function Ping-Host {
param($computername,$count)
$host.ui.rawui.windowtitle="Pinging: "+ $computername
if($count){
for($c=1; $c -le $count; $c++){
Ping-Host-Worker $computername
if($c -ne $count) {Start-Sleep -seconds 1}
if([System.Console]::KeyAvailable){break} # Break if user presses any key
}
} else {
do {
Ping-Host-Worker $computername
Start-Sleep -seconds 1
} until ([System.Console]::KeyAvailable) # Stop if user presses any key
}
$host.ui.rawui.windowtitle=$default_window_title
}
function Ping-Host-Worker($computername) {
$PingSuccessSymbol = "`u{1F7E2}" # Green Circle
$PingFailSymbol = "`u{1F534}" # Red Circle
try {
$test = Test-Connection $computername -ErrorAction Stop -count 1 # Ping Function
$test | Select-Object Address,Latency,Status # Ping Output Displayed
if($test[0].status -eq "Success"){
$host.ui.rawui.windowtitle= $PingSuccessSymbol+" Pinging: "+ $computername # Update Window Title
} else {
$host.ui.rawui.windowtitle= $PingFailSymbol+" Pinging: "+ $computername # Update Window Title
}
}
catch [System.Net.NetworkInformation.PingException]{
Write-Host $_.Exception.Message -ForegroundColor Red # Display Exception
$host.ui.rawui.windowtitle= $PingFailSymbol+" Pinging: "+ $computername # Update Window Title
}
}
## Function: logged-in [computername]
## Return the current logged-in user of a remote machine.
function Get-Logged-In-User {
[CmdletBinding()]
param (
[Parameter(Mandatory=$True)]
[string[]]$computername
)
foreach ($pc in $computername){
$logged_in = (Get-WMIObject win32_computersystem -COMPUTER $pc).username # Retrieves the username of the remote user
$name = $logged_in.split("\")[1] # Strips the domain prefix from the username
"{0}: {1}" -f $pc,$name # Prints the PC and Username
}
}
## Function: my-ip
## Lookup internal and external IP address for local machine.
function Get-My-IP-Address {
# Look up internal IP addresses using Get-NetIPAddress
$internal = Get-NetIPAddress -AddressFamily IPv4 | Select-Object -Expand IPAddress
Write-Host "Internal: $internal"
# Look up external IP addresses by querying ifconfig.me
$external = curl -s ifconfig.me
Write-Host "External: $external"
}
## Function welcome
## Prints a welcome message dependant on the time of day.
function Get-Welcome-Message {
$currentTime = Get-Date
$hour = $currentTime.Hour
if ($hour -lt 12) {
if($myName){Write-Host "Good morning, $myName!"}else{Write-Host "Good morning!"}
} elseif ($hour -ge 12 -and $hour -lt 18) {
if($myName){Write-Host "Good afternoon, $myName!"}else{Write-Host "Good afternoon!"}
} else {
if($myName){Write-Host "Good evening, $myName!"}else{Write-Host "Good evening!"}
}
}
## Function password [length]
## Generates a random password. Defaults to 12 character password, non-ambiguous characters, including all character types.
function New-Random-Password {
param (
[int]$Length = 12,[switch]$Ambiguous,[switch]$Upper,[switch]$Lower,[switch]$Number,[switch]$Symbol,[switch]$Clip,[switch]$PlainText
)
# Define Character Sets
if($Ambiguous){
$LowerCaseLetters = 'abcdefghijklmnopqrstuvwxyz'
$UpperCaseLetters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
$Numbers = '0123456789'
$Symbols = '!@#$%^&*()-_=+[]{}|;:,.<>?/'
} else {
$LowerCaseLetters = 'abcdefghjkmnpqrstuvwxyz'
$UpperCaseLetters = 'ABCDEFGHJKLMNPQRSTUVWXYZ'
$Numbers = '23456789'
$Symbols = '!@#$%^&*()-_=+[]{}|;:,.<>?/'
}
if(! ($Upper -or $Lower -or $Number -or $Symbol)){
# If no flags are set, activate all character sets
$Upper = $true
$Lower = $true
$Number = $true
$Symbol = $true
}
# Generate the Character Set
$CharacterSet = ""
if($Upper) { $CharacterSet += $UpperCaseLetters }
if($Lower) { $CharacterSet += $LowerCaseLetters }
if($Number) { $CharacterSet += $Numbers }
if($Symbol) { $CharacterSet += $Symbols }
# Guarantee at least one of each character type appears in password
$Password = $null
if($Upper) { $password += ($UpperCaseLetters -Split "" | Where-Object { $_ -ne '' } | Get-Random) }
if($Lower) { $password += ($LowerCaseLetters -Split "" | Where-Object { $_ -ne '' } | Get-Random) }
if($Number) { $password += ($Numbers -Split "" | Where-Object { $_ -ne '' } | Get-Random) }
if($Symbol) { $password += ($Symbols -Split "" | Where-Object { $_ -ne '' } | Get-Random) }
# Adjust length
$Length = $Length - $Password.Length
# Protect against negative length passwords
if($Length -lt 0) { $Length = 0 }
# Generate Random Bytes
$Random = New-Object System.Security.Cryptography.RNGCryptoServiceProvider
$Bytes = New-Object byte[] ($Length)
$Random.GetBytes($Bytes)
# Generate Password from Random Bytes
$Password += -join ($Bytes | ForEach-Object { $CharacterSet[$_ % $CharacterSet.Length] })
# Shuffle the characters in the password
$Password = $Password.ToCharArray() | Get-Random -Count $Password.Length
$Password = $Password -join ""
if($Clip) {
Set-Clipboard -Value $Password
} elseif($PlainText) {
return $Password
} else {
Write-Colorized-String $Password
}
}
function Write-Colorized-String{
param (
[string]$InputString
)
foreach ($char in $InputString.ToCharArray()) {
switch -Wildcard ($char) {
'[0-9]' { Write-Host -NoNewline $char -ForegroundColor Cyan }
'[A-Z]' { Write-Host -NoNewline $char -ForegroundColor Yellow }
default { Write-Host -NoNewline $char -ForegroundColor Red}
}
}
Write-Host
}
## Set Window Title
$host.ui.rawui.windowtitle=$default_window_title
## Print Welcome Message
Get-Welcome-Message