Powershell Foreach Loop Is Using My Files - powershell

I have the following code
$top = Get-ChildItem -File C:\SomeFolder\1\ -Recurse -filter *.evtx
foreach ($file in $top) {
$get = (Get-WinEvent -Path C:\SomeFolder\1\$file -erroraction 'silentlycontinue').count
if ($get -eq '0') {
Remove-Item -Path C:\SomeFolder\1\$file -Recurse -Force
}
}
The problem is that the files that I'm trying to delete are in use by the loop.
The following error appears - "Remove-Item : Cannot remove item The process cannot access the file because it is being used by another process."
I even tried exiting with break but it didn't help.
Any suggestions?
Thanks!

Related

Get-childitem is not working with foreach loop

Trying to delete files from multiple path,
So have created a csv file like path,days,filter
importing this file in shell and looping over each object to delete contents, but getchilditem is failing again and again,
Unable to understand reason behind that,
Below is the code what m trying to achieve
Start-Transcript -Path "D:\delete.log"
$pathlist= Import-csv -LiteralPath "D:\diskpath.csv"
$count = 0
foreach($p in $pathlist){
Write-host $p.path " | " $p.days -ForegroundColor DarkCyan
$path = $p.path
$days = $p.days
$filter = $p.filter
Get-ChildItem -Path $path -Filter $filter | where-object{$_.LastWriteTime -lt [datetime]::Now.AddDays(-$days)}|Remove-Item -Force -Verbose -Recurse -ErrorAction SilentlyContinue -Confirm $false
}
Stop-Transcript
without for loop, script executes properly, but with for loop it fails
Please let know if any further information needed on this query,
will like provide the same,
have already google and read multiple questions here at SO, but unable to find reason behind failure,
#T-Me and #Theo
Thanks for highlighting error, haven't looked type error in script my bad, whereas while manual typing in PowerShell was writing correctly, but in script made mistake, now its working-
Start-Transcript -Path "D:\delete.log"
$pathlist= Import-csv -LiteralPath "D:\diskpath.csv"
$count = 0
foreach($p in $pathlist){
Write-host $p.path " | " $p.days -ForegroundColor DarkCyan
$path = $p.path
$days = $p.days
$filter = $p.filter
Get-ChildItem -Path $path -Filter $filter | where-object{$_.LastWriteTime -lt [datetime]::Now.AddDays(-$days)}|Remove-Item -Force -Verbose -Recurse
}

How to move files based on filename using PowerShell?

I am new to PowerShell and am stuck at something.
How to move files based on filename using PowerShell?
Move 0001_ddmmyy_username[active1]_L_kkkkk.pdf to C:\Users\abc\London
Move 0001_ddmmyy_jacky[active1]_R_kkkkk.pdf to C:\Users\abc\Russia
Move 0001_ddmmyy_jim[active1]_P_kkkkk.pdf to C:\Users\abc\Poland
I used the following code to move files to a folder called London. It fails if the file name has any square bracket with text [kkkk].
gci 'C:\Users\abc' -Recurse -Include "*_L*" | %{ Move-Item $_.FullName 'C:\Users\abc\London'}
How can I automate this?
There are multiple ways:
Get-Location
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-location?view=powershell-7
gci (Get-Location).Path
or simply .\
gci .\
additionaly, gci will default to current path if none is specified. So the following will get the current folder:
gci
Use -LiteralPath in the Move-Item cmdlet.
Move-Item -LiteralPath $sourcePath $destinationPath
I'd do something similar to below:
# Note I'm using -File so it only returns files
$items = gci .\ -Recurse -File -Include *_L*, *_R*, *_P*
foreach($item in $items) {
# Could utilize something cleaner/better but this will do
if($item.Name -like "*_L*") {
Move-Item -LiteralPath $item 'C:\Users\abc\London'
} elseif($item.Name -like "*_R*") {
Move-Item -LiteralPath $item 'C:\Users\abc\Russia'
} elseif ($item.Name -like "*_P*") {
Move-Item -LiteralPath $item 'C:\Users\abc\Poland'
} else {
# Unexpected output
Write-Host "The path did not match what was expected"
Write-Host $item.Name
}
}
Windows 10 64-bit. PowerShell 5.
How to move files based on file basename using PowerShell gci, foreach, if, -like, move-item and -literalpath
Move 0001_ddmmyy_username[active1]_L_kkkkk.pdf to C:\Users\abc\London
Move 0001_ddmmyy_jacky[active1]_R_kkkkk.pdf to C:\Users\abc\Russia
Move 0001_ddmmyy_jim[active1]_P_kkkkk.pdf to C:\Users\abc\Poland
Change $env:userprofile\desktop. Remove -whatif when you are satisfied it works.
$items = gci -recurse -file *_L_*, *_R_*, *_P_*
foreach($item in $items) {
# Change $env:userprofile\desktop
if($item -like "*_L_*") {
Move-Item -LiteralPath $item "$env:userprofile\desktop\London" -whatif
} elseif($item -like "*_R_*") {
Move-Item -LiteralPath $item "$env:userprofile\desktop\Russia" -whatif
} elseif ($item -like '*_P_*') {
Move-Item -LiteralPath $item "$env:userprofile\desktop\Poland" -whatif
}
}
Comments:
With some cmdlets you will get odd results when you use -Path and any part of the full file name contains []. The fix is to use the -LiteralPath parameter. See Get-Help Move-Item -Parameter *path* – Lee_Dailey
How to move files based on file basename using PowerShell gci, foreach, if, -like, move-item and -literalpath

Powershell exclude items when copying not working

I am willing to copy recursively from one dir to another by excluding some items that cause errors if copied.
It was working fine when I only had the "System Volume..." and "RECYCLE.BIN" values in "$Excluir" variable, but, now I need to exclude every item that starts with a dot "." so I wrote the loop you see after it that adds new values to the $Excluir variabl.
Now the "-Exclude" parameter forgets excluding the new values, in this case these values are names of files and directories that start with a dot "."
Sorry if my english causes confusions.
This is my code:
$RutaOrigenFicheros = "E:\"
$RutaTempFicheros = "A:\ENTRADA\TMP\"
$Excluir = #( "System Volume Information","`$RECYCLE.BIN")
$ElementosOcultosUnix = Get-ChildItem $RutaOrigenFicheros -Name -Recurse -Include ".*"
foreach ($i in $ElementosOcultosUnix){
if ($i -match "\\")
{
$elemento = $i -split "\\"
$n = ($elemento.length) - 1
$Excluir += $elemento[$n]
}
else
{
$Excluir += $i
}
}
Write-Host $Excluir
Copy-Item -Path $RutaOrigenFicheros* -Destination $RutaTempFicheros -Recurse -Force -Exclude $Excluir -ErrorAction Stop
Your logic isn't very clear (or doesn't make sense). Here's what I think you're trying to accomplish with your code:
$Destination='A:\Temp\'
$Exclude = Get-ChildItem -Path 'E:\' -Recurse -Force |
Where-Object { $_.FullName -like '*System Volume Information*' -or
$_.FullName -like '*$RECYCLE.BIN*' -or
$_.FullName -like '*\.*' }
Write-Host $Exclude.FullName
Copy-Item -Path 'E:\*' -Destination $Destination -Recurse -Force -Exclude $Exclude.FullName -ErrorAction 'Stop'

Script to get ERROR and WARN lines

I'm trying to get all the ERROR and WARN lines to files with the name of an object, like the following:
$items = Get-ChildItem -Path "C:\Test"
foreach ($item in $items)
{
gci $item *.log* -rec -Force -ErrorAction SilentlyContinue |
Select-String "WARN|ERROR" >> "C:\MyDir$item.Name_logTest.txt"
}
However, the recursive flag doesn't allow me to go over all folders.
EDIT: Guys, I figured it out. Instead of using "gci $item", I used "gci $item.PSPath"
ForEach ($Item in (Get-ChildItem -Path "C:\Test" -filter "*.log" -recurse)) {...

Powershell - remove files

This script will only delete files if all exists. How to rewrite the script, so it will delete files even one of the file is missing.
$paths = $outpath, $outPath2, $outPath3
if ((test-path $paths) -notcontains $false){
Remove-Item -Path $paths
}
If the problem is the error exception when it doesn't find a file , you can use the remove-item parameter -erroraction silentlycontinue :
$paths| % { Remove-Item "$_" -ErrorAction SilentlyContinue }