-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdelete-user.ps1
74 lines (60 loc) · 2.51 KB
/
delete-user.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
# Get the script's directory and filename without the .ps1 extension
$scriptPath = $MyInvocation.MyCommand.Path
$scriptDir = Split-Path -Parent $scriptPath
$scriptKey = [IO.Path]::GetFileNameWithoutExtension($scriptPath)
# Path to the config file
$configFilePath = Join-Path -Path $scriptDir -ChildPath "config.json"
# Check if the config file exists
if (-Not (Test-Path -Path $configFilePath)) {
Write-Error "Configuration file not found at $configFilePath."
# Prevent the window from closing after the program ends
Write-Host "Press any key to close this window..."
[void][System.Console]::ReadKey()
exit 1
}
# Load and parse the JSON config file
try {
$configData = Get-Content -Path $configFilePath -Raw | ConvertFrom-Json
} catch {
Write-Error "Failed to parse the configuration file as JSON: $_"
# Prevent the window from closing after the program ends
Write-Host "Press any key to close this window..."
[void][System.Console]::ReadKey()
exit 1
}
# Extract the section corresponding to the script's filename
if (-Not $configData.$scriptKey) {
Write-Error "The '$scriptKey' section is missing in the configuration file."
# Prevent the window from closing after the program ends
Write-Host "Press any key to close this window..."
[void][System.Console]::ReadKey()
exit 1
}
$config = $configData.$scriptKey
# Define the folder and share name for new share
$username = $config.username
# Ensure running as admin
$currentUser = [Security.Principal.WindowsIdentity]::GetCurrent()
$adminRole = [Security.Principal.WindowsBuiltInRole]::Administrator
$isAdmin = (New-Object Security.Principal.WindowsPrincipal($currentUser)).IsInRole($adminRole)
if (-not $isAdmin) {
Write-Host "Restarting PowerShell as administrator..."
Start-Process -FilePath "powershell.exe" -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs
# Prevent the window from closing after the program ends
Write-Host "Press any key to close this window..."
[void][System.Console]::ReadKey()
exit
}
# Check if the user exists
$userExists = Get-LocalUser -Name $username -ErrorAction SilentlyContinue
if ($userExists) {
Write-Output "Deleting User '$username'."
Remove-LocalUser -Name $username
Write-Output "User '$username' deleted."
} else {
Write-Output "User '$username' not found."
}
# Prevent the window from closing after the program ends
Write-Host "Press any key to close this window..."
[void][System.Console]::ReadKey()
exit