Created
August 13, 2024 03:28
-
-
Save nanoDBA/4fd5eaeb396e213e9546ebdf34477068 to your computer and use it in GitHub Desktop.
This script accesses files stored in a directory, reading the first 1024 bytes of each file. It includes a function that carefully removes comments marked by /* and */ from the content. After cleaning up the content, it converts it back into bytes and saves the changes to the original files.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| $files = Get-ChildItem -Path "A:\Phoenix" | |
| # Define the comment start and end markers | |
| $commentStart = '/*' | |
| $commentEnd = '*/' | |
| foreach ($file in $files) { | |
| # Open the file and read the first 1024 bytes | |
| $maxBytes = 1024 | |
| $buffer = New-Object byte[] $maxBytes | |
| $fs = [System.IO.File]::OpenRead($file.FullName) | |
| $bytesRead = $fs.Read($buffer, 0, $maxBytes) | |
| $fs.Close() | |
| # Convert bytes to string | |
| $firstBytes = [System.Text.Encoding]::UTF8.GetString($buffer, 0, $bytesRead) | |
| # Remove comments | |
| function Remove-Comments { | |
| param ( | |
| [string]$text, | |
| [string]$startMarker, | |
| [string]$endMarker | |
| ) | |
| $pattern = [regex]::Escape($startMarker) + ".*?" + [regex]::Escape($endMarker) | |
| return [regex]::Replace($text, $pattern, '', [System.Text.RegularExpressions.RegexOptions]::Singleline) | |
| } | |
| # Apply the removal function | |
| $cleanedBytes = Remove-Comments -text $firstBytes -startMarker $commentStart -endMarker $commentEnd | |
| # Convert the cleaned content back to bytes | |
| $cleanedBytes = [System.Text.Encoding]::UTF8.GetBytes($cleanedBytes) | |
| # Write the updated bytes back to the file | |
| $fs = [System.IO.File]::Open($file.FullName, [System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite) | |
| $fs.Write($cleanedBytes, 0, $cleanedBytes.Length) | |
| $fs.Close() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment