deleting log files with powershell - powershell

I have a powershell script which deletes log files but not the locked ones. The files are open with notepad++. Not sure what else to add. Any suggestions?
$logpath = "C:\logs"
Get-ChildItem $logpath -recurse | Remove-Item -force

Your best bet here would probably be to use the sysinternals application handle to get the process ID of the file that is locked and then close that process before continuing with the deletion.

i was able to get it to work by adding a pipeline to exclude the folder and its contents instead of deleting it.

Related

Powershell Script: Search for BATs with specific name and run them

back with another request to try and make my life a little easier. The problem: one of the programs I use deposits BMPs (yes, bitmaps, this is an ancient app, and no, I can't configure it not to make BMPs) where I don't need them. I've got a BAT file that can sweep a folder and remove them, but what I'd really like to do is put a copy of said BAT file in each folder where it leaves them, and then every time I run a backup cycle, have it search for those BAT files, and wherever it finds one, run it. (I'd also need to know how to tell it "look in the same folder you're in"--I think I can do that by something like $searchfolder = "." but please correct me if I'm wrong)
I'm guessing this is a Get-Childitem and ForEach, but I've taken a few stabs at it and it won't work. Does anyone have an idea how to go about it?
This is what I've got so far for the parent script to find all instances of "Clear_BMPs.bat":
Get-ChildItem $sourceDir -Include Clear_BMPs.bat -Recurse | ForEach-Object { call "Clear_BMPs.bat" }
And this is what I've got in the child script, to get rid of the BMPs themselves (the filename for it is "Clear_BMPs.bat":
$searchfile = "*.bmp"
$targetdir = ".\"
Get-ChildItem $targetdir -Include $searchfile | foreach{ "Removing file $($_.FullName)"; Remove-Item -force $_}
I'm still trying to get the Clear_BMPs.bat files to work properly but in my vision it will only search the root of the folder it's in, and not recurse through subdirectories.
Since you're calling from PowerShell, there's no reason to involve batch files, given that the code is under your control.
Indeed, what you show as the content of a Clear_BMPs.bat batch file is PowerShell code, which means you need to store it in a .ps1 file, not a .bat file.
Therefore, your recursive invocation that executes all .ps1 files should look like this:
# Find all 'Clear_BMPs.ps1' scripts in the subdir. tree of $sourceDir
# and invoke them.
Get-ChildItem -Recurse -LiteralPath $sourceDir -Filter Clear_BMPs.ps1 |
ForEach-Object { & $_.FullName }
And the Clear_BMPs.ps1 files in the various directories should contain:
# Remove all *.bmp files from the same dir. in which this .ps1 script is located.
Remove-Item -Path "$PSScriptRoot/*.bmp"
Note the use of the automatic $PSScriptRoot variable, which refers to the directory in which the enclosing .ps1 file is located.

Powershell: copy file without locking

I created simple nagios plugin check_log.ps1 to check log file on windows machine. It works in way that make copy content of log and in next time look for specified string in difference between copy of log and original log file.
The problem is that sometimes in random moments check_log.ps1 locks log file so it cause stop of the application which create log file.
Generally plugin use original log file in two places
# compare content of $Logfile and $Oldlog, save diff to $tempdiff
Compare-Object -ReferenceObject (Get-Content -Path $Logfile) -DifferenceObject (Get-Content -Path $Oldlog) | Select-Object -Property InputObject > $tempdiff
# override file $Oldlog using conetent of $Logfile
Copy-Item $Logfile $Oldlog
I make test. In one PS session I run while($true) { [string]"test" >> C:\test\test.log }, in second session I run plugin C:\test\check_log.ps1 C:\test\test.log C:\test\Old_log.log test
I'm not fully sure if my test is correct but I think that Copy-Item command cause problem. When I comment this line in script I don't see any errors in terminals. I tested some custom functions to copy file which I found in internet but I din't find solution for my problem.
Do you have an idea how to make it work fully?
if you think the copy-item is locking the file, try reading the content and then saving it to another location. Something like this:
Get-Content $Logfile | Set-Content $Oldlog

Force Remove a Folder in-use using Powershell

I've created a script which at the end deletes all the associated files, self-destructs by deleting itself, and then it's supposed to delete the folder it is contained in as well.
I've tried several ways of closing Windows Explorer, searching through active processes and killing any related processes, but still cannot successfully delete the folder despite being able to self-destruct the script itself.
Set-Location -Path $PSScriptRoot
Remove-Item -Path $PSScriptRoot\Mobile -Force -Recurse
Remove-Item -Path $PSScriptRoot\NoMobile -Force -Recurse
Remove-Item -Path $MyInvocation.MyCommand.Source -Force -Recurse
Set-Location ..
Remove-Item $foldername -Force -Recurse
The last line throws an error that "The process cannot access the file...because it is being used by another process".
Any thoughts?
This may be not the answer you might be expecting right now but posting it so that it might be helpful if someone comes into this thread.
I happen to face issue in deleting the file then after help from co-worker I found that file was open in the editor or on some other user machine. I got to follow the below document to find out who had the file open and then close those files and tried to perform delete operation and this time it worked as expected. Please find the document to figure out who happen to have the file open which you are trying to delete.
https://techgoeasy.com/how-to-tell-who-has-a-file-open-in-windows/

PowerShell Active Directory Login Script Auto-Build

I've created an active directory account creation script using powershell 4.
My Boss has stated there's a new policy where we have to build a login script per user, is there a way to do this where it'll build the .bat file and map the drives that we specify within the script?
I know there's a way to build .txt files, but not sure about .bat.
What I need
Select Drives That The user Needs Access To
I need it to build a .bat file, mapping the drives previously specified.
Then move it to the login script folder on the DC, mapped to S
For Future reference to anybody who wants to do this.
I've managed to resolve it myself after some playing around.
$NewName = $SAMAccountName
$extension = ".bat"
$FileName = "$SAMAccountName$extension"
$ScriptDrive = "\\IPREMOVED\scripts"
Write-Output "
BAT CONTENTS" `n`n|FT -AutoSize >>LoginScript.txt
Get-ChildItem LoginScript.txt | Rename-Item -NewName $FileName
Move-Item -Path ".\$FileName" -Destination $ScriptDrive

Exclude Folder and contents when using Get-ChildItem

I need some help with a powershell script to exclude certain folders and files.
I have it written so far that it ignores shortcuts and a folder called data, but when the delete command runs, it also deletes all of the content's of the Data folder on the users desktop.
This is the essential part of what I have
$exclude = ('*.lnk', "*data*")
{Get-ChildItem -Path ([environment]::GetFolderPath("Desktop")) -Exclude $exclude -Recurse | Remove-Item -Force -Recurse}
How can I best achieve what I want, this is to have the script run at each startup, remove all desktop content apart from shortcuts and the Data folder+contents. The contents could be anything from exe to mp3 and I do not want to just exclude MP3 from deletion as I may well want them removed from other folders that have been placed on the desktop.
regards