Skip to content

Commit b695b44

Browse files
Add files via upload
1 parent bda7c02 commit b695b44

19 files changed

+1720
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# PowerShell Script Explanation
2+
3+
This script is designed to scan through the output of the `tree` command on Windows, searching for mentions of various antivirus software names within the directory structure. It then reports back on which antivirus names were found.
4+
5+
## Code Breakdown
6+
7+
### Defining Antivirus Names List
8+
9+
```powershell
10+
$antivirusNames = @("Norton", "McAfee", "Avast", "AVG", "Bitdefender", "Kaspersky", "ESET", "Sophos", "TrendMicro", "Comodo", "Panda", "Avira", "F-Secure", "GData", "Malwarebytes", "Spybot", "ZoneAlarm", "Webroot", "IObit")
11+
```
12+
13+
This section initializes an array `$antivirusNames` containing strings of popular antivirus software names. This list serves as the criteria against which the script will match the contents of directories listed by the `tree` command.
14+
15+
### Checking for `tree` Command Availability
16+
17+
```powershell
18+
if (-not (Get-Command tree -ErrorAction SilentlyContinue)) {
19+
Write-Host "ERROR: Tree command not found. Please install or use an alternative method."
20+
exit
21+
}
22+
```
23+
24+
The script checks if the `tree` command is available on the system. If not, it outputs an error message and exits. The `-ErrorAction SilentlyContinue` parameter ensures that any errors encountered during this check do not halt the execution of the script.
25+
26+
### Capturing and Processing `tree` Output
27+
28+
```powershell
29+
$treeOutput = tree /f
30+
$lines = $treeOutput -split "`n"
31+
```
32+
33+
Here, the script executes the `tree` command with `/f` flag to display the directory structure in full format. The output is captured into the variable `$treeOutput`. Then, the output is split into individual lines using the newline character (`\n`) as a delimiter, storing these lines in the `$lines` array.
34+
35+
### Removing Duplicate Antivirus Names
36+
37+
```powershell
38+
$antivirusNames = $antivirusNames | Sort-Object | Get-Unique
39+
```
40+
41+
Before processing, the script sorts the `$antivirusNames` array and removes any duplicate entries using `Sort-Object` and `Get-Unique`, ensuring that each name is unique and processed only once.
42+
43+
### Progress Tracking and Matching
44+
45+
```powershell
46+
$completedLines = 0
47+
$foundAntivirus = @()
48+
foreach ($line in $lines) {
49+
$completedLines++
50+
foreach ($name in $antivirusNames) {
51+
if ($line -match "\b$name\b") {
52+
$foundAntivirus += $name
53+
}
54+
}
55+
}
56+
```
57+
58+
For each line in the `$lines` array, the script increments a counter `$completedLines` to track progress. It then iterates over each antivirus name in the `$antivirusNames` array, checking if the current line contains the name as a whole word (ensured by `\b` word boundary markers). If a match is found, the name is added to the `$foundAntivirus` array.
59+
60+
### Reporting Results
61+
62+
```powershell
63+
Write-Host "Processed $completedLines lines."
64+
if ($foundAntivirus.Count -gt 0) {
65+
Write-Host "INFO: Found Antivirus:"
66+
$foundAntivirus | Sort-Object -Unique | ForEach-Object { Write-Host $_ }
67+
} else {
68+
Write-Host "INFO: No antivirus found."
69+
}
70+
```
71+
72+
Finally, the script prints out how many lines it has processed. If any antivirus names were found, it lists them uniquely; otherwise, it informs that no antivirus names were found.
73+
74+
## Conclusion
75+
76+
This script provides a basic example of text processing in PowerShell, demonstrating how to search for specific patterns across multiple lines of text, track progress, and report findings. It can be adapted for various text-based analysis tasks beyond just scanning for antivirus software names.
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
# PowerShell Script for Renaming and Moving Folders Based on User Data
2+
3+
This script automates the process of copying and renaming folders based on user data from various applications and system locations. It's particularly useful for backing up or analyzing user-specific data without manual intervention.
4+
5+
## Code Breakdown
6+
7+
### Defining Source Paths and Identifiers
8+
9+
```powershell
10+
$sourcePaths = @(
11+
"C:\Users\{}\AppData\Local\Microsoft\Edge\User Data\Default\Network",
12+
"C:\Users\{}\AppData\Local\Google\Chrome\User Data\Default\Network",
13+
"C:\Users\{}\AppData\Roaming\Mozilla\Firefox\Profiles",
14+
"C:\Users\{}\AppData\Roaming\Opera Software\Opera Stable\Network",
15+
"C:\Users\{}\AppData\Roaming\Opera Software\Opera GX Stable\Network",
16+
'C:\\WINDOWS\\system32\\config\\SAM',
17+
'C:\\Windows\\System32\\config',
18+
'C:\\Windows\\System32\\GroupPolicy',
19+
'C:\\Windows\\System32\\GroupPolicyUsers',
20+
'C:\\Windows\\System32\\winevt\\Logs'
21+
)
22+
```
23+
24+
This section defines an array `$sourcePaths` containing strings representing the paths to various user data directories and system configuration files. Each path includes a placeholder `{}` that will be replaced with the current user's username.
25+
26+
### Defining Identifiers for Renaming
27+
28+
```powershell
29+
$identifiers = @(
30+
"Edge",
31+
"Chrome",
32+
"Firefox",
33+
"OperaStable",
34+
"OperaGXStable",
35+
"SAM",
36+
"SystemConfig",
37+
"GroupPolicy",
38+
"GroupPolicyUsers",
39+
"WindowsEventLogs"
40+
)
41+
```
42+
43+
An array `$identifiers` is defined to hold the names by which the copied folders will be renamed. These names correspond to the types of data being copied, making it easier to identify the purpose of each folder later.
44+
45+
### Getting Current User Name
46+
47+
```powershell
48+
$currentUser = $env:USERNAME
49+
```
50+
51+
The script retrieves the current user's username from the environment variable `USERNAME` and stores it in the variable `$currentUser`.
52+
53+
### Base Directory for Destination
54+
55+
```powershell
56+
$baseDirectory = "DATA"
57+
```
58+
59+
A string `$baseDirectory` is set to `"DATA"`, indicating that the destination for the copied folders will be a directory named `DATA`.
60+
61+
### Main Loop Through Source Paths
62+
63+
```powershell
64+
foreach ($sourcePath in $sourcePaths) {
65+
...
66+
}
67+
```
68+
69+
The script iterates over each source path defined in `$sourcePaths`. For each path, it performs several operations:
70+
71+
#### Replacing Placeholder with Username
72+
73+
```powershell
74+
$fullSourcePath = $sourcePath -replace '\{\}', $currentUser
75+
```
76+
77+
The placeholder `{}` in each source path is replaced with the actual username of the current user, creating a fully qualified path to the user's data.
78+
79+
#### Checking Path Existence and Readability
80+
81+
```powershell
82+
if (-not (Test-Path $fullSourcePath -PathType Container -ErrorAction SilentlyContinue)) {
83+
...
84+
}
85+
```
86+
87+
The script checks if the constructed path exists and is accessible. If not, it issues a warning and skips to the next iteration.
88+
89+
#### Extracting Identifier from Source Path
90+
91+
```powershell
92+
$identifier = $sourcePath.Split('\')[-1].Split('\\')[-1]
93+
```
94+
95+
By splitting the source path and extracting the last segment, the script determines the type of data being copied, which corresponds to an entry in the `$identifiers` array.
96+
97+
#### Setting Destination Path and Creating If Necessary
98+
99+
```powershell
100+
$destinationPath = Join-Path -Path $baseDirectory -ChildPath "USER_$identifier"
101+
...
102+
New-Item -ItemType Directory -Path $destinationPath -Force | Out-Null
103+
```
104+
105+
The script constructs the destination path by joining the base directory with a new child path that includes the identifier. If the destination directory does not exist, it creates it.
106+
107+
#### Copying and Renaming Folder
108+
109+
```powershell
110+
try {
111+
Copy-Item -Path $fullSourcePath -Destination $destinationPath -Recurse -Force -ErrorAction SilentlyContinue
112+
...
113+
} catch {
114+
...
115+
}
116+
```
117+
118+
Finally, the script attempts to copy the entire content of the source path to the destination path, including subdirectories and files. If successful, it logs the operation. In case of any error, it suppresses the error message and logs a generic error message instead.
119+
120+
## Conclusion
121+
122+
This script is a practical tool for managing user data backups or analyses by automating the process of copying and renaming folders based on user-specific data. It demonstrates effective use of PowerShell for file manipulation, path construction, and error handling.
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
# Python Script Using PyAutoGUI and ColorLog for Automating System Tasks
2+
3+
This Python script demonstrates the automation of several system-level actions using the `pyautogui` library, along with logging capabilities provided by `colorlog`. The script simulates pressing keys and mouse buttons to perform tasks such as opening the Run dialog, typing a command to enable the command prompt, executing the command, and closing the command prompt window. Throughout the process, it uses colored logging to provide feedback on its operations.
4+
5+
## Key Elements
6+
7+
### Importing Libraries
8+
9+
```python
10+
import pyautogui
11+
import time
12+
import colorlog
13+
```
14+
15+
The script begins by importing the necessary libraries:
16+
- `pyautogui`: A module used for programmatically controlling the mouse and keyboard.
17+
- `time`: Provides functions for working with time, including pausing the script execution.
18+
- `colorlog`: Allows for colored terminal output, enhancing readability and distinguishing between different levels of log messages.
19+
20+
### Setting Up Logging
21+
22+
```python
23+
# Create a logger
24+
logger = colorlog.getLogger()
25+
logger.setLevel(colorlog.INFO) # Set the log level
26+
27+
# Define a handler that outputs logs to console
28+
handler = colorlog.StreamHandler()
29+
formatter = colorlog.ColoredFormatter(
30+
"%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s",
31+
datefmt=None,
32+
reset=True,
33+
log_colors={
34+
'DEBUG': 'cyan',
35+
'INFO': 'green',
36+
'WARNING': 'yellow',
37+
'ERROR': 'red',
38+
'CRITICAL': 'red,bg_white',
39+
}
40+
)
41+
handler.setFormatter(formatter)
42+
logger.addHandler(handler)
43+
```
44+
45+
This section configures a logger with `colorlog` to output log messages in color, making them easier to read and distinguish based on their severity level.
46+
47+
### Functions for Automation
48+
49+
#### Press Win+R
50+
51+
```python
52+
def press_win_r():
53+
pyautogui.hotkey('win', 'r')
54+
logger.info("Simulated pressing Win+R to open the Run dialog.")
55+
```
56+
57+
Simulates pressing the Windows key + R to open the Run dialog box.
58+
59+
#### Type Command
60+
61+
```python
62+
def type_command():
63+
pyautogui.write(
64+
'cmd.exe /k "REG add HKCU\\Software\\Policies\\Microsoft\\Windows\\System /v DisableCMD /t REG_DWORD /d 0 /f"')
65+
logger.info("Typed the command to enable the command prompt.")
66+
```
67+
68+
Type a command to enable the command prompt via the Registry Editor.
69+
70+
#### Press Enter
71+
72+
```python
73+
def press_enter():
74+
pyautogui.press('enter')
75+
logger.info("Pressed Enter to execute the command.")
76+
```
77+
78+
Simulates pressing the Enter key to execute the previously typed command.
79+
80+
#### Press Alt+F4
81+
82+
```python
83+
def press_alt_f4():
84+
pyautogui.hotkey('alt', 'f4')
85+
logger.info("Simulated pressing Alt+F4 to close the command prompt window.")
86+
```
87+
88+
Simulates pressing Alt+F4 to close the currently active window, in this case, the command prompt window opened by the previous commands.
89+
90+
### Main Execution Flow
91+
92+
```python
93+
if __name__ == "__main__":
94+
# Wait a bit to ensure the script is ready to run
95+
time.sleep(2)
96+
97+
press_win_r()
98+
99+
# Wait a bit for the Run dialog to appear
100+
time.sleep(1)
101+
102+
type_command()
103+
104+
press_enter()
105+
106+
# Wait a bit for the command to execute and the command prompt to open
107+
time.sleep(2)
108+
109+
press_alt_f4()
110+
111+
logger.info(
112+
"INFO: Command executed to enable the command prompt and the window has been closed. Mouse and keyboard have been re-enabled.")
113+
```
114+
115+
The main part of the script waits briefly before starting the sequence of actions. It opens the Run dialog, types a command to enable the command prompt, executes the command, and finally closes the command prompt window. After completing these steps, it logs a final informational message indicating the completion of the task.
116+
117+
## Conclusion
118+
119+
This script showcases how `pyautogui` can be used for automating interactions with the operating system at a low level, combined with `colorlog` for enhanced logging. While this specific example focuses on enabling the command prompt, similar techniques can be applied to automate a wide range of tasks involving keyboard and mouse inputs.

EXPLAIN/Clean Explained.md

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# PowerShell Script to Automatically Delete 'DATA' Directories
2+
3+
This script is designed to automatically find and delete all directories named 'DATA' within the current working directory. It's a straightforward utility for cleaning up temporary or backup data stored in such directories.
4+
5+
## Code Breakdown
6+
7+
### Getting the Current Working Directory
8+
9+
```powershell
10+
$currentWorkingDir = Get-Location
11+
```
12+
13+
The script starts by determining the current working directory using `Get-Location` and storing it in the variable `$currentWorkingDir`.
14+
15+
### Defining the Target Directory Name
16+
17+
```powershell
18+
$directoryName = "DATA"
19+
```
20+
21+
It then sets a variable `$directoryName` to `"DATA"`, specifying that the script will focus on directories with this exact name.
22+
23+
### Listing All Directories in the Current Working Directory
24+
25+
```powershell
26+
$directories = Get-ChildItem -Directory
27+
```
28+
29+
Using `Get-ChildItem` with the `-Directory` parameter, the script retrieves a list of all directories within the current working directory and stores them in the `$directories` variable.
30+
31+
### Looping Through Each Directory
32+
33+
```powershell
34+
foreach ($dir in $directories) {
35+
...
36+
}
37+
```
38+
39+
The script iterates over each directory found in the previous step. For each directory, it performs a check to see if the directory's name matches the target name.
40+
41+
### Checking for Match and Deleting the Directory
42+
43+
```powershell
44+
if ($dir.Name -eq $directoryName) {
45+
...
46+
}
47+
```
48+
49+
If the current directory's name exactly matches the target name ("DATA"), the script proceeds to attempt deletion.
50+
51+
#### Attempting to Delete the Directory
52+
53+
```powershell
54+
try {
55+
Remove-Item -Recurse -Force $dir.FullName
56+
Write-Host "INFO: '$($dir.FullName)' has been deleted."
57+
} catch {
58+
Write-Host "ERROR: Failed to delete '$($dir.FullName)': $_"
59+
}
60+
```
61+
62+
Within a `try` block, the script uses `Remove-Item` with the `-Recurse` and `-Force` parameters to attempt to delete the directory and all its contents. If successful, it logs a success message. If an error occurs (e.g., the directory is in use), it catches the exception and logs an error message detailing the failure.
63+
64+
### Completion Message
65+
66+
```powershell
67+
Write-Host "INFO: Script completed. All 'DATA' directories found have been deleted."
68+
```
69+
70+
Upon completion of the loop, the script logs a final informational message indicating that all targeted 'DATA' directories have been successfully deleted.
71+
72+
## Conclusion
73+
74+
This script is a simple yet effective tool for managing cleanup tasks related to specific directory names within the current working directory. It demonstrates basic PowerShell techniques for directory traversal, conditional logic, and error handling when performing file system operations.

0 commit comments

Comments
 (0)