Write a Program for windows for i have a data in the folder if any user read that data for 3 times need delete the data in that folder completely
Assistant
To create a Windows program that monitors if files in a folder are read 3 times and then deletes the data in that folder, you can write a script that tracks file reads.
However, natively detecting when a user reads a file is not straightforward because "read" can mean many things (opening in an editor, copying, etc.), and Windows does not provide an easy event hook specifically for that.
One approach is:
Use Windows file system auditing to detect read access events and parse the Windows Security log to count reads, then delete files when threshold reached.
Use a user-mode program that acts as a proxy or monitors file open/read events with tools like Windows Filter Manager (a kernel-mode filter driver) — but this is complex.
Another approach is to monitor file open operations for read access via a FileSystemWatcher and some additional tricks, but FileSystemWatcher doesn't track file reads, only changes.
So with pure managed code or script, this is very hard. However, here's a compromise simpler solution:
Use a program that runs in the background and hooks into the Windows Event Log to count the number of times files in the folder were accessed.
For this, Windows auditing on the folder must be enabled for read access.
Here's a step-by-step approach:
Enable auditing on the target folder for read access.
Write a program in C# (recommended) that listens to Security Event Log for file read events on that folder and maintains a count.
When total read count reaches 3, delete folder contents.
Alternatively, if you want a simpler solution ignoring OS-level auditing, you can write a program that records opening of files through itself; for example, a program that allows users to open files through its UI, counts how many times files were opened, and deletes folder contents after 3 reads.
I will show an example of this second approach using C# console app—assuming the user accesses file through the program.
C# Console Program to open files and count reads
csharp
using System;
using System.Collections.Generic;
using System.IO;
class Program
{
// Keeps track of how many times files have been read
static Dictionary<string, int> fileReadCounts = new Dictionary<string, int>();
static int totalReads = 0;
const int maxReads = 3;
static void Main(string[] args)
{
string folderPath = @"C:\Path\To\Your\Folder";
if (!Directory.Exists(folderPath))
{
Console.WriteLine($"Folder does not exist: {folderPath}");
return;
}
Console.WriteLine("Files in folder:");
var files = Directory.GetFiles(folderPath);
for (int i = 0; i < files.Length; i++)
{
Console.WriteLine($"{i + 1}. {Path.GetFileName(files[i])}");
fileReadCounts[files[i]] = 0;
}
while (true)
{
Console.WriteLine("Type file number to read or 'exit' to quit:");
var input = Console.ReadLine();
if (input.ToLower() == "exit")
break;
if (int.TryParse(input, out int fileIndex))
{
if (fileIndex < 1 || fileIndex > files.Length)
{
Console.WriteLine("Invalid file number.");
continue;
}
string selectedFile = files[fileIndex - 1];
ReadFile(selectedFile);
totalReads++;
if (totalReads >= maxReads)
{
Console.WriteLine($"Files have been read {maxReads} times. Deleting all files...");
DeleteAllFiles(folderPath);
break;
}
}
else
{
Console.WriteLine("Invalid input.");
}
}
Console.WriteLine("Program exiting.");
}
static void ReadFile(string path)
{
try
{
string content = File.ReadAllText(path);
Console.WriteLine($"--- Content of {Path.GetFileName(path)} ---");
Console.WriteLine(content);
Console.WriteLine($"--- End of content ---\n");
fileReadCounts[path]++;
Console.WriteLine($"File {Path.GetFileName(path)} has been read {fileReadCounts[path]} times.");
}
catch (Exception ex)
{
Console.WriteLine($"Error reading file: {ex.Message}");
}
}
static void DeleteAllFiles(string folder)
{
try
{
var files = Directory.GetFiles(folder);
foreach (var f in files)
{
File.Delete(f);
}
Console.WriteLine("All files deleted.");
}
catch (Exception ex)
{
Console.WriteLine($"Error deleting files: {ex.Message}");
}
}
}
How this works
Displays files in folder.
User picks a file to "read" (contents printed in console).
Total number of reads across all files is tracked.
When totalReads reaches 3, deletes all files in the folder.
Notes:
This program only counts reads via itself.
To do this for arbitrary file reading by any program/user requires system-level auditing or a filter driver, which is complex.
You may want to make a service or scheduled task that reads the security logs to detect read events.
If you want me to provide example code for auditing or reading Security Event Logs, or use PowerShell to set folder access auditing, please let me know!
User
its portable application automatic enable after 3 reads
Assistant
Thanks for clarifying: you want a portable application (no install), that automatically monitors files in a given folder, counts when any user reads those files, and deletes everything in that folder after 3 total reads.
Important clarifications and constraints:
"Portable application" means it runs without installation (like a single EXE).
It should monitor file reads automatically (not via user opening files through the app).
It should delete all data in the folder after 3 read events (total, across all files).
Runs on Windows.
The challenge:
Windows does not provide a trivial way to detect "file read" events from user-mode code.
FileSystemWatcher can detect changes (created, modified, deleted) but not reads.
To monitor file reads from all processes requires:
Enabling Windows Object Access Auditing on the folder.
Parsing Windows Security Event Log for read/access events (FileSystem Object Access category).
Your app keeps track of the number of read events.
Deletes folder contents after 3 reads.
This requires administrative rights to enable auditing.
Overview of solution I recommend (in a portable console app):
You (administrator) configure Windows folder auditing once.
The portable app runs and reads Security Event Logs, filtering out read events on your folder.
The app keeps count of number of reads happened since start or since last reset.
After 3 reads, it deletes all files in folder and optionally exits.
Runs as a console app or minimized.
This is the closest you can get to an automatic, non-user-dependent read detection.
Step 1 — Enable auditing on target folder
You must manually enable auditing for read events on the folder.
Run the following PowerShell commands as Administrator (or configure via GUI):
powershell
User
is this posible to write bat file
Assistant
Monitoring file read/access events from Windows Security logs and acting on them is not feasible with just a batch (.bat) script, because:
Batch files cannot directly subscribe or listen to Windows Event Log events in real-time.
Parsing Security Event logs (Event ID 4663) for read events requires XML parsing and advanced filtering.
Deleting files after 3 reads based on event data needs persistent counting and monitoring, beyond batch file capabilities.
Parse some logs statically — but parsing and filtering Windows Security log with wevtutil or PowerShell is complex in batch.
Count events — very limited without auxiliary tools.
So: A pure batch script solution to automatically delete folder contents after 3 reads by any user is not possible because:
No simple way to detect/read the file reads from batch.
No event log monitoring and complex parsing in batch.
No persistent state handling elegantly.
Possible alternative with batch + PowerShell
You can trigger a PowerShell script from a batch file that:
Queries the Security event log for 4663 "ReadData" events on your folder
Counts how many events occurred
Deletes files if count ≥ 3
But that script then needs to be periodically run (e.g., scheduled task), not real-time via batch.
Example batch file calling a PowerShell script (periodic check):
Create a file CheckReadCount.bat with:
batch
@echo off
powershell.exe -ExecutionPolicy Bypass -File "%~dp0\CheckReadCount.ps1"
And a PowerShell script CheckReadCount.ps1 (in the same folder) to:
Read Security event log entries for 4663 events.
Filter those that have ReadData access on your folder.
Count how many reads occurred in total.
If count >= 3, delete folder files.
Very simplified example PowerShell script that you can trigger from batch:
User
write CheckReadCount.ps1
Assistant
Certainly! Below is a complete CheckReadCount.ps1 PowerShell script that:
Scans recent Windows Security event logs (Event ID 4663 – Object Access),
Filters events for ReadData access on files inside your specified folder,
Counts the number of such read events,
If reads ≥ threshold (3), deletes all files inside the folder,
Outputs status messages.
CheckReadCount.ps1
powershell
User
CheckReadCount.ps1 folder path will be where it is placed
Assistant
Sure! To have CheckReadCount.ps1 detect and monitor the folder where the script itself is placed, you can use PowerShell's automatic variable $PSScriptRoot which contains the directory path of the running script.
Here’s the updated script that sets $folderPath dynamically to the script’s folder location:
powershell
# Use folder where this script is located
$folderPath = $PSScriptRoot
# Number of reads allowed before deletion
$maxReads = 3
# How many days back to look for read events (adjust as needed)
$lookbackDays = 1
# Normalize folder path for comparison (ensure trailing backslash)
$folderPathNorm = [IO.Path]::GetFullPath($folderPath).TrimEnd('\') + '\'
# Check folder exists
if (-not (Test-Path $folderPath)) {
Write-Output "Folder not found: $folderPath"
exit 1
}
# Calculate start time for event log query
$startTime = (Get-Date).AddDays(-$lookbackDays)
try {
# Query Security event log for EventID 4663 (file access) in the lookback period
$events = Get-WinEvent -FilterHashtable @{
LogName = 'Security';
Id = 4663;
StartTime = $startTime
} -ErrorAction Stop
} catch {
Write-Output "Error reading Security event log: $_"
exit 1
}
$readEventsCount = 0
foreach ($ev in $events) {
try {
# Parse event XML to extract ObjectName and AccessList fields
$xml = [xml]$ev.ToXml()
$eventData = $xml.Event.EventData.Data
$objectName = $eventData | Where-Object { $_.Name -eq "ObjectName" } | Select-Object -ExpandProperty '#text'
$accessList = $eventData | Where-Object { $_.Name -eq "AccessList" } | Select-Object -ExpandProperty '#text'
if ([string]::IsNullOrEmpty($objectName) -or [string]::IsNullOrEmpty($accessList)) {
continue
}
# Check if access includes "ReadData" (file read)
if ($accessList -notlike "*ReadData*") {
continue
}
# Normalize object path for comparison
$objectNameNorm = [IO.Path]::GetFullPath($objectName)
# Check if accessed file is within monitored folder
if ($objectNameNorm.StartsWith($folderPathNorm, [System.StringComparison]::OrdinalIgnoreCase)) {
$readEventsCount++
}
}
catch {
# Ignoring parse errors
continue
}
}
Write-Output "Read events found in last $lookbackDays day(s): $readEventsCount"
if ($readEventsCount -ge $maxReads) {
Write-Output "Read count threshold reached. Deleting files in folder: $folderPath"
try {
Get-ChildItem -Path $folderPath -File -Recurse | Remove-Item -Force -ErrorAction Stop
Write-Output "All files deleted."
} catch {
Write-Output "Error deleting files: $_"
exit 1
}
} else {
Write-Output "Read count below threshold, no action taken."
}
User
is that posible to block all data it can not read or write or view from any software
Assistant
Blocking all read/write/view access to files in a folder by any software except certain allowed programs or users on Windows is tricky but can be done via a combination of NTFS permissions and folder access control, and sometimes via encryption or sandboxing.
What you asked:
Is it possible to block all data so it cannot be read or written or viewed from any software?
Short answer:
Yes, it is possible to restrict access such that no programs (and no users) can read or write files, by setting very restrictive NTFS permissions or encrypting the data.
However, totally blocking all access while allowing something to read or write requires careful permission design.
Windows does not have a “deny all reads” universal switch — permissions (ACLs) must be configured properly.
For complete protection, encrypting files with EFS or 3rd party encryption is commonly used.
To prevent read/write/view by any software/user, remove all NTFS permissions or deny access via ACLs.
You can use AppLocker or Software Restriction Policies to restrict which programs can run or access data.
This is more complex and usually requires Windows Pro/Enterprise version.
Third-party sandbox or encryption tools
Use solutions like VeraCrypt or other encrypted containers.
Only decrypt when you want, guaranteeing data is inaccessible otherwise.
User
where the file located place
Assistant
Great question! When using the PowerShell variable $PSScriptRoot in your script (like CheckReadCount.ps1), it contains the full directory path where the script file itself is located.
What does $PSScriptRoot mean?
If your script file is located at:
code
D:\Tools\CheckReadCount.ps1
then:
powershell
Write-Output $PSScriptRoot
will output:
code
D:\Tools
So for your script:
If you set folder path as:
powershell
$folderPath = $PSScriptRoot
it means the script will monitor and operate on the same folder where you placed CheckReadCount.ps1.
Summary:
Where you put the script
Value of $PSScriptRoot
Folder being monitored/deleted
C:\MyScripts\CheckReadCount.ps1
C:\MyScripts
C:\MyScripts
D:\DataMonitor\CheckReadCount.ps1
D:\DataMonitor
D:\DataMonitor
E:\Projects\MyApp\CheckReadCount.ps1
E:\Projects\MyApp
E:\Projects\MyApp
Note:
If you run the script directly from PowerShell ISE or console without saving (like running code snippets), $PSScriptRoot may be empty or $null.
Always save your .ps1 script to a folder and run it from there to reliably use $PSScriptRoot.
If you want to confirm folder at runtime, you can add this line in your script for debugging:
powershell
Write-Output "Monitoring folder: $folderPath"
If you want me to help with automating or placing the script in a specific folder structure, just ask!
User
rewrite properly
Assistant
Certainly! Here's a clean, properly formatted explanation about the folder location used by $PSScriptRoot in your PowerShell script, suitable for documentation or comments:
Understanding Script Location with $PSScriptRoot in PowerShell
When you use the variable $PSScriptRoot in a PowerShell script, it contains the full directory path where the script file is physically located.
Example:
If your script file is saved at:
code
C:\MyScripts\CheckReadCount.ps1
Then inside the script:
powershell
Write-Output $PSScriptRoot
Will output:
code
C:\MyScripts
Using $PSScriptRoot as the monitored folder path
If you want your script to monitor or operate on the folder where it resides, you can assign:
powershell
$folderPath = $PSScriptRoot
This makes the script automatically reference its own directory, regardless of where that is on the system.
Important notes:
$PSScriptRoot is only defined when running a saved script file. If you run commands interactively (like in PowerShell ISE or console), $PSScriptRoot may be empty or undefined.
To ensure expected behavior, always save your script file and run it from the saved location.
This practice is useful for portable scripts that you want to deploy and run from any folder without changing hardcoded paths.
Summary table
Script file location
$PSScriptRoot value
$folderPath (if set as $PSScriptRoot)
C:\Users\User\Documents\MyScripts
C:\Users\User\Documents\MyScripts
Monitors C:\Users\User\Documents\MyScripts folder
D:\Tools\
D:\Tools
Monitors D:\Tools folder
E:\Projects\PowerShellScripts
E:\Projects\PowerShellScripts
Monitors E:\Projects\PowerShellScripts folder
Example usage in your script:
powershell
# Set monitored folder to folder where this script is located
$folderPath = $PSScriptRoot
Write-Output "Monitoring folder: $folderPath"
If you want me to help integrate this into your full script or explain more, just let me know!
User
write a script that block entire folder
Assistant
Certainly! To block all access (read/write/list) to an entire folder for all users except yourself or SYSTEM, you can use PowerShell to modify the NTFS permissions on that folder.
PowerShell script to block access to a folder for Everyone
This script:
Revokes All Access from the Everyone group (denying Read, Write, ListDirectory, Delete, Modify).
Leaves access for SYSTEM and the current user intact (you can customize this).
Stops inheritance on the folder to avoid inherited permissions overriding settings.
powershell
# Folder path to block access to (change this path as needed)
$folderPath = "C:\Path\To\Your\Folder"
# Get current user SID
$currentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
# Load current ACL
$acl = Get-Acl -Path $folderPath
# Remove inheritance and copy existing inherited ACEs as explicit (optional: set $false to remove inheritance)
$acl.SetAccessRuleProtection($true, $true)
# Remove all existing explicit rules - optional if you want to start fresh
foreach($ace in $acl.Access) {
$acl.RemoveAccessRule($ace)
}
# Add Allow rules for SYSTEM and current user
# Allow full control for SYSTEM
$systemSid = New-Object System.Security.Principal.SecurityIdentifier("S-1-5-18")
$systemRule = New-Object System.Security.AccessControl.FileSystemAccessRule($systemSid,
"FullControl",
"ContainerInherit,ObjectInherit",
"None",
"Allow")
$acl.AddAccessRule($systemRule)
# Allow full control for current user
$currentUserSid = New-Object System.Security.Principal.SecurityIdentifier($currentUser)
$userRule = New-Object System.Security.AccessControl.FileSystemAccessRule($currentUserSid,
"FullControl",
"ContainerInherit,ObjectInherit",
"None",
"Allow")
$acl.AddAccessRule($userRule)
# Deny all access to Everyone group
$everyoneRule = New-Object System.Security.AccessControl.FileSystemAccessRule("Everyone",
"FullControl",
"ContainerInherit,ObjectInherit",
"None",
"Deny")
$acl.AddAccessRule($everyoneRule)
# Set the updated ACL back to the folder
Set-Acl -Path $folderPath -AclObject $acl
Write-Output "Access to folder '$folderPath' is now blocked for Everyone except SYSTEM and current user."
User
is that posible to hide all folder which can not be retrive
Assistant
Hiding a folder on Windows so that it is completely invisible and cannot be retrieved or accessed by normal means is tricky. Here’s a breakdown of what’s possible and what’s not:
What "hiding" means on Windows
Simple hide (setting Hidden attribute):
You can mark folders (or files) with the Hidden attribute.
This makes them invisible in Explorer only if "Show hidden files" is turned off (default).
This is easily bypassed by toggling the visibility option; not secure.
System attribute + Hidden attribute:
Mark folder as both Hidden + System attributes.
Explorer treats them as super-hidden, less likely shown.
Still accessible by direct path, command line, or advanced users.
NTFS permissions:
You can remove all read/list permissions for a user or everyone (deny access).
Then users cannot see or enter the folder. Effectively “hidden” from them.
But users with admin rights can override or take ownership.
Rename folder to a "special" name or inside a system folder:
E.g., prefix with $ or use CLSIDs to turn it into a virtual folder.
This is a hack, not secure.
Encrypt folder:
Encrypting folder (EFS) makes data inaccessible without proper keys.
If unauthorized users can't decrypt, folder is unreadable (practically “hidden”).
What Windows cannot do natively
Completely prevent retrieval of a folder by all means (including admin, backup tools, live forensics) without encryption or special filesystem filter driver.
You cannot truly hide a folder from all system tools and users if they have admin rights.
Your question: “Hide all folder which cannot be retrieved”
Absolute non-retrievability isn’t possible without encryption.
Recommended approaches:
1. Hide + Deny access (best combined)
powershell
User
where the file located there it need to hide all files
Assistant
Got it! You want a script that — for the folder where the script itself is located — hides all the files inside it (and optionally subfolders), making them hidden (and maybe system), so they’re not shown by default in Explorer.
What the script will do:
Target the folder where the .ps1 script is running ($PSScriptRoot)
Set Hidden (and optionally System) attributes on all files and folders inside it
This makes files and folders "super hidden" in Explorer (unless user enables “Show hidden and system files”)
PowerShell Script to hide all files and subfolders in its own folder
powershell
# Folder where this script is placed
$folderPath = $PSScriptRoot
Write-Output "Hiding all files and folders inside: $folderPath"
# Get all files AND directories recursively inside the folder
# Remove ReadOnly attribute first just in case (optional)
$items = Get-ChildItem -Path $folderPath -Recurse -Force
foreach ($item in $items) {
try {
# Remove ReadOnly attribute (optional)
if ($item.Attributes -band [System.IO.FileAttributes]::ReadOnly) {
$item.Attributes = $item.Attributes -bxor [System.IO.FileAttributes]::ReadOnly
}
# Add Hidden and System attributes
$newAttributes = $item.Attributes -bor [System.IO.FileAttributes]::Hidden -bor [System.IO.FileAttributes]::System
$item.Attributes = $newAttributes
Write-Output "Hidden: $($item.FullName)"
}
catch {
Write-Warning "Failed to hide: $($item.FullName) - $_"
}
}
Write-Output "All files and folders are now hidden (and system)."
How to use:
Save this as HideAllFiles.ps1 inside the folder you want to hide files in.
User
write a script anyone open the folder 3 times it automatically run file name called tsta.ps1
Assistant
Monitoring how many times a folder is opened by any user and then triggering a script after it’s been opened 3 times is not straightforward in Windows scripting alone, because:
Windows does not track "folder opens" as simple events accessible via scripts.
Folder opening in Explorer does not generate a simple event you can easily monitor.
There’s no native "folder opened" event that can be caught by PowerShell or batch scripts in real-time.
What can you do instead?
Windows does generate file system audit events when folder contents are accessed (if auditing for folder access is enabled). You can:
Enable audit policy to log folder access (read/list) events.
Monitor the Windows Security Event Log (event ID 4663 - object access) for read events on that folder.
Count those events (for example, counts of folder/list directory accesses correspond to opens).
When the count reaches 3, trigger your tsta.ps1 script automatically.
Limitations
This requires auditing enabled on the folder for object access.
You need permissions to read the Security Event Log.
Requires a monitoring script or program running in background or scheduled frequently.
Not perfectly "folder open" detection, but closest via read/list access on folder.
Example implementation approach:
A continuously running PowerShell script monitors the Security logs for read/list directory accesses for your monitored folder.
When total count of such events reaches 3, runs tsta.ps1.
Resets or stops monitoring after triggering.
Example simplified PowerShell script outline
powershell
User
its it posible when it open run tsta.ps1
Assistant
Running a script automatically exactly when a folder is opened (e.g., a user double-clicks the folder in Explorer) is not natively supported by Windows. Windows does not provide a built-in event or hook mechanism that triggers a script on folder-open actions.
Why is it not feasible?
Folder open in Explorer is just the Shell browsing that folder.
No simple file system or event log event fires specifically "folder opened" that user-mode scripts can hook into live.
Folder access events (like file reads) get logged after the fact in Security log if auditing enabled, but no instant trigger to run custom scripts.
No way to force Explorer or Windows to run a script automatically on user browsing a folder.
What are some possible alternatives?
Method
Description
Limitations
Use Folder as a Special Shortcut (Folder Desktop.ini run commands)
Hacky desktop.ini tricks with AutoRun commands or custom shell extensions
Limited, not reliable or supported in modern Windows
Shell extension or File System Filter driver
Develop a low-level shell extension or kernel driver to hook folder open events
Complex, requires development in C++, admin, signing
Audit folder access and poll in background
Enable auditing, monitor folder read events in Security log, run your script after N accesses
Not immediate, no real-time trigger
Replace folder with a shortcut or link to a script
Only runs script when user clicks that shortcut, but then user is not browsing folder.
Changes user experience, less transparent
Summary: You cannot run tsta.ps1 exactly at folder open in normal Windows
The closest practical solution is:
Enable auditing for folder access.
Run a background monitor script that detects when users access the folder (via Security Event Log).
After detecting N (e.g., 3) folder read events, run tsta.ps1.
Alternative user-triggered hack (not folder open, but user triggers script):
Replace the folder with a shortcut or a script file (e.g., a clickable .ps1 or ) that runs and then opens the folder.
User
i have a file name called TACCESS.TSF if this file read 3 times run tsta.ps1 automatically
Assistant
You want to monitor access (reads) of a specific file (TACCESS.TSF) and automatically run tsta.ps1 after the file has been read 3 times.
Possible approach:
Since Windows does not natively trigger scripts on file reads, the practical way is:
Enable Object Access auditing on the file so each read is logged in the Security event log (Event ID 4663).
Run a PowerShell script periodically or as a long-running process monitoring Security logs for read events on that file.
When the count reaches 3, run tsta.ps1.
Details:
Step 1 — Enable auditing on the file (TACCESS.TSF)
Run PowerShell as Administrator, then:
powershell
# Path to your file - change as needed
$path = "C:\Path\To\Folder\TACCESS.TSF"
# Enable auditing of file reads
# First enable file system auditing in system (one time, admin)
auditpol /set /subcategory:"File System" /success:enable /failure:disable
# Add audit rule to file for "Everyone" or specific user, Success read access
$acl = Get-Acl $path
$rule = New-Object System.Security.AccessControl.FileSystemAuditRule("Everyone","ReadData","None","None","Success")
$acl.AddAuditRule($rule)
Set-Acl -Path $path -AclObject $acl
Step 2 — PowerShell monitoring script
Save as MonitorFileReads.ps1 (change paths as needed):
powershell
User
rite script in condition where the file is
Assistant
Certainly! Below is a complete PowerShell script that:
Automatically detects the folder where the script is located ($PSScriptRoot).
Monitors read accesses to the file named TACCESS.TSFin that same folder.
After the file is read 3 times, runs tsta.ps1 located in the same folder.
Complete MonitorFileReads.ps1
powershell
# Folder where this script is located
$scriptFolder = $PSScriptRoot
# Target file and trigger script paths
$targetFile = Join-Path $scriptFolder "TACCESS.TSF"
$triggerScript = Join-Path $scriptFolder "tsta.ps1"
# Max number of reads before triggering
$maxReads = 3
# Normalize path for comparison
$targetFileNorm = [IO.Path]::GetFullPath($targetFile)
# Counter for read events
$readCount = 0
Write-Output "Monitoring read events for file:`n $targetFile"
# Track last timestamp checked to avoid duplicate processing
$lastCheckTime = Get-Date
while ($true) {
try {
# Get Security log events for 4663 starting from last check
$events = Get-WinEvent -FilterHashtable @{
LogName = 'Security'
Id = 4663
StartTime = $lastCheckTime
} -ErrorAction SilentlyContinue
foreach ($ev in $events) {
$xml = [xml]$ev.ToXml()
$data = $xml.Event.EventData.Data
$objectName = ($data | Where-Object { $_.Name -eq "ObjectName" }).'#text'
$accessList = ($data | Where-Object { $_.Name -eq "AccessList" }).'#text'
if ([string]::IsNullOrEmpty($objectName) -or [string]::IsNullOrEmpty($accessList)) {
continue
}
$objectNameNorm = [IO.Path]::GetFullPath($objectName)
# Check for exact file path and "ReadData" access
if ( ($objectNameNorm -eq $targetFileNorm) -and ($accessList -like "*ReadData*") ) {
$readCount++
Write-Output "[$(Get-Date)] Detected read #$readCount on $targetFile"
if ($readCount -ge $maxReads) {
Write-Output "Read threshold reached. Running $triggerScript"
# Run the trigger script
& powershell.exe -ExecutionPolicy Bypass -File $triggerScript
exit
}
}
}
# Update lastCheckTime to now to avoid reprocessing old events
$lastCheckTime = Get-Date
# Wait before next polling
Start-Sleep -Seconds 5
}
catch {
Write-Warning "Error during monitoring: $_"
Start-Sleep -Seconds 10
}
}
User
create batch file
Assistant
Certainly! Here's a simple batch file that runs your PowerShell monitoring script (MonitorFileReads.ps1) located in the same folder.
Create file: RunMonitor.bat
batch
@echo off
REM Run MonitorFileReads.ps1 from the batch file location
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0MonitorFileReads.ps1"
pause
Explanation:
%~dp0 is the directory path where the batch file is located, so it runs MonitorFileReads.ps1 from the same folder.
Using -NoProfile for faster launch without loading user profiles.
-ExecutionPolicy Bypass to allow script execution without policy blocks.
pause keeps the window open after script finishes/errors (remove if you want it to close automatically).
How to use:
Save this text in a file named RunMonitor.bat
Place it in the same folder as MonitorFileReads.ps1, tsta.ps1, and TACCESS.TSF.
Double-click RunMonitor.bat to start monitoring.
Ensure you run the batch file as Administrator (right-click → Run as Administrator) to have permissions required for reading Security logs.
If you want a version without pause or with minimized window, or to run on startup, just ask!
User
can it posible to make a script that deleted inside files text or data entirely in the files without loosing file names
Assistant
Yes, it's definitely possible to create a script that clears the contents of all files inside a specified folder while keeping the original filenames intact (i.e., the files themselves remain, but their contents are emptied).
Here's a simple PowerShell script that does exactly that:
PowerShell script: ClearContents.ps1
powershell
# Path to the folder - change this as needed
$folderPath = "C:\Path\To\Your\Folder"
if (-not (Test-Path $folderPath)) {
Write-Error "Folder does not exist: $folderPath"
exit 1
}
# Get all files inside folder (non-recursive)
$files = Get-ChildItem -Path $folderPath -File
foreach ($file in $files) {
try {
# Clear file contents without deleting the file
Set-Content -Path $file.FullName -Value $null
Write-Output "Cleared contents of file: $($file.Name)"
}
catch {
Write-Warning "Could not clear file: $($file.Name), error: $_"
}
}
Write-Output "Finished clearing contents of all files in $folderPath"
How it works
The script iterates through every file in the folder.
For each file, it writes no content ($null) to it, effectively emptying the file.
The file remains with its original name, but the data inside is erased.
It does not recurse into subfolders, but this can be added if needed.
This operation cannot be undone. Make sure you have backups if needed.
It will try to clear all files regardless of type or content.
If some files are in use or protected, clearing might fail for them.
If you want a batch or VBScript version or have other custom requirements (e.g., only clear .txt files), let me know!
User
write script where it is
Assistant
Certainly! Below is a PowerShell script that clears the contents of all files located in the same folder as the script itself (without deleting the files or changing their names):
ClearContents.ps1 (clears all files in script folder)
powershell
# Get the folder where this script is located
$folderPath = $PSScriptRoot
if (-not (Test-Path $folderPath)) {
Write-Error "Folder does not exist: $folderPath"
exit 1
}
Write-Output "Clearing contents of all files inside folder: $folderPath"
# Get all files in the folder (non-recursive)
$files = Get-ChildItem -Path $folderPath -File
foreach ($file in $files) {
try {
# Clear the file contents
Set-Content -Path $file.FullName -Value $null
Write-Output "Cleared: $($file.Name)"
}
catch {
Write-Warning "Failed to clear file $($file.Name): $_"
}
}
Write-Output "Completed clearing contents of all files."
Usage:
Save the above as ClearContents.ps1 inside the folder where your files are.
If you want a batch script or need additional filters (like only clearing .txt files or excluding some files), just ask!
User
Above need to run automatically once any changes in TACCESS.TSF date madified
Assistant
You want a script that automatically clears the contents of all files in the script folder whenever the file TACCESS.TSF in that folder is modified (i.e., its timestamp changes).
How to implement this?
Since PowerShell can monitor file system changes using Register-ObjectEvent, we can watch TACCESS.TSF for changes and trigger the clearing script once a modification is detected.
Complete PowerShell script to monitor TACCESS.TSF modification and clear all files in the script’s folder:
powershell
# Path variables
$folderPath = $PSScriptRoot
$watchFile = Join-Path $folderPath "TACCESS.TSF"
Write-Output "Monitoring file: $watchFile for changes..."
if (-not (Test-Path $watchFile)) {
Write-Error "File to watch not found: $watchFile"
exit 1
}
# Create FileSystemWatcher object to monitor the target file for changes
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $folderPath
$watcher.Filter = [IO.Path]::GetFileName($watchFile)
$watcher.NotifyFilter = [IO.NotifyFilters]'LastWrite'
# Action to run when file modified event triggered
$action = {
# Debounce to prevent multiple triggers in short time
# Unregister event to prevent reentry
Unregister-Event -SourceIdentifier FileChangedEvent | Out-Null
Write-Output "Detected modification of TACCESS.TSF with timestamp: $(Get-Date)"
# Clear contents of all files in script folder
Get-ChildItem -Path $using:folderPath -File | ForEach-Object {
try {
Set-Content -Path $_.FullName -Value $null
Write-Output "Cleared contents of: $($_.Name)"
}
catch {
Write-Warning "Failed to clear file $($_.Name): $_"
}
}
Write-Output "All files cleared due to TACCESS.TSF modification."
# Re-register event to continue watching
Register-ObjectEvent -InputObject $using:watcher -EventName Changed -SourceIdentifier FileChangedEvent -Action $using:action | Out-Null
}
# Register the event handler
Register-ObjectEvent -InputObject $watcher -EventName Changed -SourceIdentifier FileChangedEvent -Action $action | Out-Null
# Start watching
$watcher.EnableRaisingEvents = $true
Write-Output "Press Ctrl+C to stop monitoring."
# Keep script running
while ($true) {
Start-Sleep -Seconds 5
}
User
TACCESS.TSF access timing Changed also need to delete
Assistant
You want to monitor any change in the TACCESS.TSF file—including content changes and metadata changes such as last access time or modified time—and whenever such a change happens, clear the contents of all files in the script’s folder.
Problem with last access time changes:
FileSystemWatcher does NOT monitor last access time changes, because last access updates are generally metadata changes that don't raise filesystem change notifications.
FileSystemWatcher monitors:
Creation
Modification (last write)
Deletion
Renaming
But last access time changes do not trigger these events.
What you can do:
1. Use FileSystemWatcher to monitor file modifications.
2. Additionally, poll the file's last access time every few seconds and check if it has changed. If changed, treat as a trigger.
Complete combined PowerShell script
powershell
User
in above if system restart it need to fun automatically
Assistant
To have your PowerShell monitoring script run automatically at system startup (i.e., after a reboot), you can configure it as a scheduled task or place a shortcut in the Startup folder.
Using a Scheduled Task is the most reliable and flexible approach, especially for scripts that require Administrator privileges or long-running monitoring.
Step-by-step: Make the script run automatically at system startup via Scheduled Task
Assuming your script WatchAccessClear.ps1 is stored at:
code
C:\Path\To\Your\Folder\WatchAccessClear.ps1
1. Create a Scheduled Task to run the PowerShell script at startup:
Open an elevated PowerShell prompt (Run as Administrator) and run the following script, or create a .ps1 file for this:
The publish folder contains a portable EXE (MonitorReadsApp.exe) you can run anywhere (as long as .NET runtime installed).
Notes:
This program requires that you have enabled auditing and that Windows is logging those events correctly.
The app reads the Security event log — on many systems, regular users cannot read this log; the app must be run with admin or equivalent permissions.
You should test with monitoring a test folder and reading files in that folder (e.g., open in Notepad) to verify events are detected.
This solution is "portable" in the sense no installation needed — just run the EXE and it monitors.
Summary:
Step
What you do
1
Enable auditing for read events on your folder
2
Run the above program as admin or user with rights to read Security log
3
The program counts read events in real time
4
When 3 reads happen, program deletes all files inside folder and exits
If you want me to help with:
Step-by-step instructions to enable auditing via GUI or scripts
PowerShell script to automate enabling auditing
How to check if audit events appear in your Security log
Let me know!
powershell
$folderPath = "C:\Path\To\Your\Folder"
$maxReads = 3
# Get 4663 events for some recent period (e.g. last 1 day)
$startTime = (Get-Date).AddDays(-1)
# Query security events for 4663 (file object access)
$events = Get-WinEvent -FilterHashtable @{
LogName='Security';
Id=4663;
StartTime=$startTime
} -ErrorAction SilentlyContinue
# Filter events for your folder and ReadData access
$readEvents = @()
foreach ($ev in $events) {
$xml = [xml]$ev.ToXml()
$objectName = $xml.Event.EventData.Data | Where-Object { $_.Name -eq "ObjectName" } | Select-Object -ExpandProperty '#text'
$access = $xml.Event.EventData.Data | Where-Object { $_.Name -eq "AccessList" } | Select-Object -ExpandProperty '#text'
if ($objectName -and $access -and ($access -like "*ReadData*")) {
if ($objectName.StartsWith($folderPath, [System.StringComparison]::OrdinalIgnoreCase)) {
$readEvents += $ev
}
}
}
if ($readEvents.Count -ge $maxReads) {
Write-Output "Read threshold exceeded. Deleting files in $folderPath"
Get-ChildItem -Path $folderPath -File | Remove-Item -Force
} else {
Write-Output "Read count below threshold: $($readEvents.Count)"
}
Usage:
Run the batch file manually or schedule it to run every X minutes via Task Scheduler.
Make sure auditing is enabled as described earlier.
Summary:
What you want
Possible with batch alone?
Recommended approach
Monitor file reads real-time
No
Use a C#/PowerShell program monitoring Security log
Delete files after 3 reads
Yes, but after detection
Use PowerShell or C# to detect reads and delete
Portable, no install
Yes, via standalone exe or batch + PowerShell scripts
If you want, I can help you build this PowerShell + batch checker script in more detail, and also how to enable Windows folder auditing properly. Just let me know!
# Path of the folder to monitor (change this accordingly)
$folderPath = "C:\Path\To\Your\Folder"
# Number of reads allowed before deletion
$maxReads = 3
# How many days back to look for read events (adjust as needed)
$lookbackDays = 1
# Normalize folder path for comparison (ensure trailing \)
$folderPathNorm = [IO.Path]::GetFullPath($folderPath).TrimEnd('\') + '\'
# Check folder exists
if (-not (Test-Path $folderPath)) {
Write-Output "Folder not found: $folderPath"
exit 1
}
# Calculate start time for event log query
$startTime = (Get-Date).AddDays(-$lookbackDays)
try {
# Query Security event log for EventID 4663 (file access) in the lookback period
$events = Get-WinEvent -FilterHashtable @{
LogName = 'Security';
Id = 4663;
StartTime = $startTime
} -ErrorAction Stop
} catch {
Write-Output "Error reading Security event log: $_"
exit 1
}
$readEventsCount = 0
foreach ($ev in $events) {
try {
# Parse event XML to extract ObjectName and AccessList fields
$xml = [xml]$ev.ToXml()
$eventData = $xml.Event.EventData.Data
$objectName = $eventData | Where-Object { $_.Name -eq "ObjectName" } | Select-Object -ExpandProperty '#text'
$accessList = $eventData | Where-Object { $_.Name -eq "AccessList" } | Select-Object -ExpandProperty '#text'
if ([string]::IsNullOrEmpty($objectName) -or [string]::IsNullOrEmpty($accessList)) {
continue
}
# Check if access includes "ReadData" (file read)
if ($accessList -notlike "*ReadData*") {
continue
}
# Normalize object path for comparison
$objectNameNorm = [IO.Path]::GetFullPath($objectName)
# Check if accessed file is within monitored folder
if ($objectNameNorm.StartsWith($folderPathNorm, [System.StringComparison]::OrdinalIgnoreCase)) {
$readEventsCount++
}
}
catch {
# Ignoring parse errors
continue
}
}
Write-Output "Read events found in last $lookbackDays day(s): $readEventsCount"
if ($readEventsCount -ge $maxReads) {
Write-Output "Read count threshold reached. Deleting files in folder: $folderPath"
try {
Get-ChildItem -Path $folderPath -File -Recurse | Remove-Item -Force -ErrorAction Stop
Write-Output "All files deleted."
} catch {
Write-Output "Error deleting files: $_"
exit 1
}
} else {
Write-Output "Read count below threshold, no action taken."
}
How to use
Update the $folderPath variable in the script to your folder.
For automation, create a .bat file that calls this PowerShell script:
batch
@echo off
powershell.exe -ExecutionPolicy Bypass -File "%~dp0CheckReadCount.ps1"
Set up a Task Scheduler task to run this batch or script every 5-10 minutes to periodically check read count.
Prerequisites and notes:
Enable auditing on your folder for read events (see previous message for setup).
The user running the script needs permission to read the Security event log — usually requires running as Administrator.
The script looks back 1 day by default ($lookbackDays), tune this if you want longer periods.
The script counts all reads matching criteria in the lookback period, so every time it runs it will count cumulative reads over that window.
To avoid repeatedly deleting files on every run after threshold is met, you could incorporate some persistence (e.g., writing a marker file after deletion). Otherwise you could just disable the scheduled task after the deletion happened.
If you want help setting up auditing or a scheduled task, just ask!
Summary:
$folderPath = $PSScriptRoot sets folder path to folder where script is located.
No need to hardcode paths; you can place the script together with your data folder.
Run the script from any location — it dynamically picks its own folder.
If you want a batch wrapper to run this PowerShell script, an example CheckReadCount.bat can be:
batch
@echo off
powershell.exe -ExecutionPolicy Bypass -File "%~dp0CheckReadCount.ps1"
This will run your .ps1 script from the same directory as the batch file.
Let me know if you want help setting up auditing or scheduling automatic runs!
Important considerations:
Administrator accounts can override permissions unless you take special measures.
You cannot prevent the SYSTEM or admin users from changing permissions or accessing files.
Your app or user needs read/write permissions to function; restricting all access means even your app can’t read or write.
If files are encrypted or permission-blocked, any program including malware won’t be able to read or write.
Windows does not natively support "blocking read but allow write" etc. permissions at fine granularity easily.
What you can do practically for your use case:
Set folder NTFS permissions to deny read/write for all users except a specific user or app.
Run your program as that specific user.
Disable inheritance of permissions on the folder and set explicit denies for Everyone.
When access must be revoked, your program can remove its own access by modifying permissions.
Example to deny access for Everyone using PowerShell:
powershell
$folder = "C:\Path\To\Your\Folder"
# Get current ACL
$acl = Get-Acl $folder
# Create deny read/write rule for Everyone
$denyRule = New-Object System.Security.AccessControl.FileSystemAccessRule("Everyone",
"Read,Write,ListDirectory",
"ContainerInherit,ObjectInherit",
"None",
"Deny")
# Add deny rule
$acl.AddAccessRule($denyRule)
# Set the ACL back
Set-Acl -Path $folder -AclObject $acl
This denies Everyone read/write/list access.
You must be careful because Deny rules override Allow rules.
You can add explicit Allow rules for specific users/apps if needed.
Summary
Goal
Feasibility with Windows NTFS and tools
Block all read/write/view access to folder
Yes, by setting deny permissions to Everyone + inheritance off
Allow only specific apps/users access
Possible by precise NTFS ACL configuration
Prevent admin/SYSTEM from overriding access
Not really — admins can always take ownership and reset ACLs
Prevent read by any software automatically
Not without encryption or sandboxing
Final thoughts
For best data protection against unauthorized reading/viewing, encrypt files.
For preventing accidental or casual access, set strict NTFS permissions.
To monitor reads as you wanted earlier, combine with auditing.
Fully blocking any access including system-level or admin requires specialized encryption or hardware protection (like BitLocker).
If you want, I can help you write PowerShell scripts or GUI steps to configure NTFS permissions securing your folder, or recommend encryption tools — just ask!
What this script does
Disables inheritance on the folder, so only explicit permissions apply.
Removes all current explicit permissions (clean slate).
Grants FullControl to:
SYSTEM account
The currently logged-in user who runs this script
Denies FullControl to Everyone group — effectively blocking all other users/processes.
The ContainerInherit,ObjectInherit flags ensure permissions apply to all files/subfolders recursively.
Important notes
Run this script as administrator, otherwise modifying ACLs may fail.
The current user running the script retains full access — change $currentUserSid if you want to allow other users instead.
Deny permissions override allow permissions; this means anyone in Everyone gets denied access no matter what other groups they might belong to.
Administrators can always override permissions by taking ownership.
Use with caution — blocking all access may lock you out if you change $currentUser or forget who can access.
How to use
Update $folderPath to the folder you want to block access for.
Save as BlockFolderAccess.ps1
Run PowerShell as Administrator
Execute the script:
powershell
.\BlockFolderAccess.ps1
If you want me to provide a reverse script to restore default permissions or remove the deny rule, just ask!
# Example: Hide folder and deny access
$folder = "C:\Path\To\MyFolder"
# Set Hidden and System attributes
attrib +h +s $folder
# Deny Everyone read/list permissions (run as admin)
$acl = Get-Acl $folder
$denyRule = New-Object System.Security.AccessControl.FileSystemAccessRule("Everyone",
"Read,ReadAndExecute,ListDirectory",
"ContainerInherit,ObjectInherit",
"None",
"Deny")
$acl.AddAccessRule($denyRule)
Set-Acl $folder $acl
This makes folder hidden and unreadable by normal users.
Admins can still override but typical users won't see or enter it.
If you want a script to also deny permissions or encrypt while hiding, I can help with that too. Just let me know!
# Folder to monitor (set to script location folder)
$folderPath = $PSScriptRoot
# Target script to run
$triggerScriptPath = Join-Path $folderPath "tsta.ps1"
# Max opens allowed before trigger
$maxOpens = 3
# Counter of folder access events
$accessCount = 0
Write-Output "Monitoring folder opens on $folderPath"
# Query for recent folder access events (or loop with delay in real use)
while ($true) {
# Query Security log for Folder Read or List Directory events (4663).
# This is a simplification - real filter may be more complex.
# Get events since last check time or last X minutes
$startTime = (Get-Date).AddMinutes(-5)
$events = Get-WinEvent -FilterHashtable @{
LogName = 'Security';
Id = 4663;
StartTime = $startTime
} -ErrorAction SilentlyContinue
foreach ($ev in $events) {
$xml = [xml]$ev.ToXml()
$data = $xml.Event.EventData.Data
$objectName = ($data | Where-Object { $_.Name -eq "ObjectName" }).'#text'
$accessMask = ($data | Where-Object { $_.Name -eq "AccessMask" }).'#text'
if (-not $objectName) { continue }
# Check if object accessed is folderPath or inside folderPath
$folderNorm = [IO.Path]::GetFullPath($folderPath).TrimEnd('\') + '\'
$objectNorm = [IO.Path]::GetFullPath($objectName)
if ($objectNorm -like "$folderNorm*") {
# Check for access mask or access list indicating folder/list directory read - simplified check
# Possible values to check: generic_read, list_directory, read_attributes, etc.
# Increment count for access assumed as folder open
$accessCount++
Write-Output "Folder access event #$accessCount detected for $objectName"
if ($accessCount -ge $maxOpens) {
Write-Output "Max folder opens reached! Running tsta.ps1"
& powershell.exe -ExecutionPolicy Bypass -File $triggerScriptPath
exit
}
}
}
Start-Sleep -Seconds 10
}
Important notes:
This is a conceptual example, real life requires refining event filtering.
Running in an infinite loop is not optimal — better as a service or triggered scheduled task.
Audit folder access must be enabled (like shown in earlier messages).
Script requires high privileges to read Security logs.
Summary
You cannot reliably detect “folder open” in real-time with a simple script.
The best approach is audit folder accesses and monitor Security logs.
After 3 reads (or similar), run your script.
If you want, I can help you write the full ready-to-use monitoring script with instructions how to enable auditing on your folder. Would you like that?
.bat
tsta.ps1
This means the user has to run your script to get into folder contents.
Not automatic on regular folder access.
If you want, I can provide:
A PowerShell "monitor" script that watches folder access events and runs tsta.ps1 after N detections.
Instructions on how to enable auditing on your folder.
A sample shortcut/script launcher approach.
Would you like me to prepare the monitor script and instructions?
$targetFile = "C:\Path\To\Folder\TACCESS.TSF"
$maxReads = 3
$triggerScript = "C:\Path\To\Folder\tsta.ps1"
# Normalize path with full qualified path (no trailing slash)
$targetFileNorm = [IO.Path]::GetFullPath($targetFile)
# Store count of detected reads
$readCount = 0
Write-Output "Monitoring read events for file: $targetFile"
# Track last time checked
$lastCheckTime = Get-Date
while ($true) {
# Query Security event log for Event ID 4663 after lastCheckTime
$events = Get-WinEvent -FilterHashtable @{
LogName = 'Security';
Id = 4663;
StartTime = $lastCheckTime
} -ErrorAction SilentlyContinue
foreach ($ev in $events) {
try {
$xml = [xml]$ev.ToXml()
$data = $xml.Event.EventData.Data
$objectName = ($data | Where-Object { $_.Name -eq "ObjectName" }).'#text'
$accessList = ($data | Where-Object { $_.Name -eq "AccessList" } ).'#text'
if ([string]::IsNullOrEmpty($objectName) -or [string]::IsNullOrEmpty($accessList)) { continue }
# Normalize path string
$objectNameNorm = [IO.Path]::GetFullPath($objectName)
# Check if event matches target file and access includes ReadData
if ($objectNameNorm -eq $targetFileNorm -and $accessList -like "*ReadData*") {
$readCount++
Write-Output "Read count for $targetFile: $readCount"
if ($readCount -ge $maxReads) {
Write-Output "Read threshold reached. Running $triggerScript"
powershell.exe -ExecutionPolicy Bypass -File $triggerScript
exit
}
}
}
catch {
# ignore parsing errors
continue
}
}
# Update lastCheckTime to now for next poll
$lastCheckTime = Get-Date
# Sleep a bit before next scan
Start-Sleep -Seconds 5
}
How to use:
Adjust paths to your TACCESS.TSF and tsta.ps1 files in the script.
Run MonitorFileReads.ps1 as Administrator (to access Security event log).
When TACCESS.TSF is read 3 times, tsta.ps1 will run automatically.
You can run this monitor script at startup or as needed.
Notes:
This script polls logs every 5 seconds, which is simple but effective.
It counts cumulative reads after script start.
You may want to save state in a file to count across runs if needed.
Proper auditing on the file is critical for this to work.
Running as admin is required to read Security logs.
If you want, I can help you with:
A version that saves and loads the read count.
Automatic startup configuration.
Steps to enable file auditing via GUI if preferred.
Let me know!
How to use:
Put this MonitorFileReads.ps1 script in the same folder as TACCESS.TSF and tsta.ps1.
Run PowerShell as Administrator (needed to read Security log).