Search code examples
powershellpowershell-2.0

Doubts about code to remove part of the text in PowerShell


I have the following code that I found on a website, it monitors a folder and saves a log in .csv. However, I need the log to contain only the name of the file I saved, without the path and extension

### SET FOLDER TO WATCH + FILES TO WATCH + SUBFOLDERS YES/NO
$Watcher = New-Object System.IO.FileSystemWatcher
$Watcher.Path = "C:\Users\some_profile\Desktop\iguaracu_pr"
$Watcher.IncludeSubdirectories = $true
$Watcher.EnableRaisingEvents = $true  

### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
$Action = {
  $Path = $Event.SourceEventArgs.FullPath
  $ChangeType = $Event.SourceEventArgs.ChangeType
  $LogLine = "$ChangeType, $Path"
  Add-Content "C:\Users\some_profile\Pictures\Duvidas\log.csv" -Value $LogLine
}
    
### DECIDE WHICH EVENTS SHOULD BE WATCHED 
Register-ObjectEvent $Watcher "Created" -Action $Action
Register-ObjectEvent $Watcher "Changed" -Action $Action
Register-ObjectEvent $Watcher "Deleted" -Action $Action
Register-ObjectEvent $Watcher "Renamed" -Action $Action

while ($true) {sleep 5}

I tried to use some codes I found on another forum but they didn't work, I hope someone with more knowledge can help me


Solution

  • According to https://learn.microsoft.com/en-us/dotnet/api/system.io.filesystemeventargs?view=net-8.0 it looks like you need to change FullPath to Name to just get the file without the path information.

    That still leaves you with the file extension. If this was a straight forward Get-ChildItem output you could simply query BaseName rather than Name to get the filename without the extension, but in this instance I don't think that's an option, which just leaves doing a string replacement to remove the last characters from the name. Not tested, but this may do the trick.

    ### DEFINE ACTIONS AFTER AN EVENT IS DETECTED
        $action = { $path = $Event.SourceEventArgs.Name
                    $path = $path -replace ".{4}$"
                    $changeType = $Event.SourceEventArgs.ChangeType
                    $logline = "$changeType, $path"
                    Add-content "C:\Users\rodrigo.lurnadelli\Pictures\Duvidas\log.csv" -value $logline
                  }  
    

    Note, the -replace just removes the last four characters from the end of the filename, eg .txt, which assumes the file has a normal 3 character extension. If it is a longer extension then you'll still have some of the extension showing. For instance myfile.jpg becomes myfile, but myfile.jpeg becomes myfile.