Powershell command doesnt find files/folder - powershell

Hello I am facing an issue with a script given here by #zett42
PowerShell search recursively for files and folder which the name contains "..."
$DesktopPath = [Environment]::GetFolderPath("Desktop")
$searchPath = '\\?\E:\Network Shares\Commun'
Get-ChildItem -LiteralPath $searchPath -Recurse -File |
Where-Object Fullname -like '*(case*' |
New-DestinationPath -CommonPath $searchPath -Destination "$home\desktop\conflits" -WhatIf | Move-Item -LiteralPath { $_.Path } -Destination { $_.Destination } -WhatIf
For example there is a complete path ;
E:\Network Shares\Commun\DOSSIER COMMUN\OFFRES EN COMMUN\ENGRAM 5000\5520 - Ecole Communale drièle**(case conflict)** - 2022-09-03T011223.317039Z\(subfolders ...)
But the command doesn't find files / folders, my network share contains a lot of long paths.
And it contains also some special characters like éèà etc.
Can you help me to adapt the command to find the unfound files/folders please ?
Thanks by advance :)

Related

Move all even files to different directory | Powershell and regex

I'm trying to move all even files from the current location to the directory "foo", but I have a problem matching them with regex.
Filenames are in this format:
11.txt, 121.txt, 342.txt
The command I'm currently using is:
Get-ChildItem | Where-Object {$_.Name -match '^[0-9]*[02468]$'} | Move-Item -Destination .\foo
The previous command I was using works OK but only for two-digit files 1.txt-99.txt
Get-ChildItem | Where-Object {$_.Name -match '^[0-9]+[02468]'} | Move-Item -Destination .\foo
I tried at https://regex101.com/ site with .NET flavor and checked this regex ^[0-9]*[02468]$ and it works OK - matches all even numbers, but for some reason, I have a problem with above mention PS command...
An alternate method I have used previously for odds/evens is a division method. The solution Santiago has provided in the comments is also a valid regex method for this problem.
# Gets files and starts loop on files
Get-ChildItem "C:\Temp\AllFiles" -File | ForEach-Object {
# If the BaseName of file is divisible by 2, else
If($_.BaseName % 2 -eq 0) {
Move-Item -Destination "C:\Temp\Evens" -Path $_.FullName
} Else {
Move-Item -Destination "C:\Temp\Odds" -Path $_.FullName
}
}

Get ChildItem from only files of specific folders

I try to export files of specific named Folders:
Get-ChildItem -Path 'C:\Test' -Name -Recurse -File > C:\Test\Test.txt
I get a list like:
content.csv
Test.txt
Folder 1\INTERESTED_FOLDER\a - Kopie.txt
Folder 1\INTERESTED_FOLDER\a.txt
Folder 1\Neuer Ordner\ttt.txt
Folder 1\Neuer Ordner - Kopie\ttt.txt
Folder 2\INTERESTED_FOLDER\b - Kopie.txt
Folder 2\INTERESTED_FOLDER\b.txt
Folder 2\Neuer Ordner\ttt.txt
Folder 2\Neuer Ordner - Kopie\ttt.txt
But what i want is:
Folder 1\INTERESTED_FOLDER\a - Kopie.txt
Folder 1\INTERESTED_FOLDER\a.txt
Folder 2\INTERESTED_FOLDER\b - Kopie.txt
Folder 2\INTERESTED_FOLDER\b.txt
I tried with -Filter "INTERESTED" etc. but then i only get
C:\Test\Folder 1\INTERESTED_FOLDER
C:\Test\Folder 2\INTERESTED_FOLDER
What i do wrong?
If I read your question correctly, you want the FullNames of the files (so their names including the path).
If that is the case, remove the -Name switch and filter on the DirectoryName property like:
(Get-ChildItem -Path 'C:\Test' -Recurse -File |
Where-Object { $_.DirectoryName -match 'INTERESTED_FOLDER' }).FullName | # also matches 'MY_INTERESTED_FOLDER_123'
Set-Content -Path 'C:\Test\Test.txt'
Alternatives for the Where-Object clause:
# also matches 'MY_INTERESTED_FOLDER_123'
Where-Object { $_.DirectoryName -like '*INTERESTED_FOLDER*' }
or if you are looking for a precise match on the complete folder name
# does NOT match 'MY_INTERESTED_FOLDER_123'
Where-Object { $_.DirectoryName -split '[/\\]' -contains 'INTERESTED_FOLDER' }
You can perform a wildcard search using the -Filter parameter:
Get-ChildItem -Path 'C:\Test' -Name -Recurse -File -Filter *INTERESTED_FOLDER* > C:\Test\Test.txt
If for example, you were interested in finding the files in INTERESTED_FOLDER but also only the files that are .txt you could do:
-Filter *INTERESTED_FOLDER*.txt
Using the -Name parameter affects your capabilities because you are returning strings instead of FileInfoObjects. You may then use Where-Object to capture everything.
Get-ChildItem -Path 'C:\Test' -Name -Recurse -File |
Where {$_ -match '\\INTERESTED_FOLDER\\'} |
Set-Content c:\test\test.txt
Note that the matching above assumes INTERESTED_FOLDER is not a direct descendent of your path. If that is a possibility, then your match expression needs to be updated to \\?INTERESTED_FOLDER\\.

Copy files located in multiple subfolder, using a mildmatch search

I have tried googling my problems for some time now, without a solution that suits my needs. So hopefully you can help me.
I have some subfolders that contain millions of files. I would like to search these subfolders for filenames containing somerandomtext.
This is what I have, but it does not copy anything to my $Newlocation folder.
$Include = #"
20190421
20190422
20190423
20190424
"#
$BaseFolder = "D:\FoldersContainingFiles"
$NewLocation = "D:\FolderForCopy\"
Get-ChildItem -Path $BaseFolder -Recurse -Include * |
Where-Object {$Include -contains $_.BaseName } |
Copy-Item -Destination $NewLocation
No error code, only no files are being moved.
Your code will only give you files that are named exactly as the example in your variable, which is:
20190421
20190422
20190423
20190424
And that is under no circumstances a valid filename.
I'm not sure what you mean by mildmatch. If you mean, that the filename of your files contains a date amongst other things, this would solve your task:
$Include = "20190421|20190422|20190423|20190424"
$BaseFolder = "D:\FoldersContainingFiles"
$NewLocation = "D:\FolderForCopy\"
Get-ChildItem -Path $BaseFolder -recurse |
Where-Object {$_.BaseName -match $Include }|
Copy-Item -Destination $NewLocation
If your filename is exactly the same as included in your variable, you can use this regex instead:
$Include = "^(20190421|20190422|20190423|20190424)$"
The rest of the code is the same.

powershell compress files within subfolder and over certain age

I have been looking around for several hours on this issue. I am looking for some help to fix this script. The Script is to search the shared folder for files in sub-folders and zip the folder up in that sub folder. What I need to also do is add the last access time of the files or folder so I can set an age to it such as 1 year or 365 days. Then 7z would remove the file after compression saving space on the server for other things.
So c:\share
c:\share\folder1
c:\share\folder2
c:\share\folder3
etc...
the script in my testing is like this
<#
.SYNOPSIS
<A brief description of the script>
.DESCRIPTION
<A detailed description of the script>
.PARAMETER <paramName>
<Description of script parameter>
.EXAMPLE
<An example of using the script>
#>
#Compress all the files based on your folder structure
Set-Location -Path 'c:\shared'
Get-ChildItem -Path 'c:\shared' -Recurse | Where-Object {$_.PSIsContainer } | ForEach-Object {
$directoryFullName = $_.FullName
$directoryName = $_.Name
Invoke-Expression -Command 'C:\7-Zip\7z.exe a "-x!*.zip" -sdel $directoryFullName\$directoryName.zip $directoryFullName\*'
}
I am trying this below but getting an error I do not understand yet as to formatting property.
<#
.SYNOPSIS
<A brief description of the script>
.DESCRIPTION
<A detailed description of the script>
.PARAMETER <paramName>
<Description of script parameter>
.EXAMPLE
<An example of using the script>
#>
#Compress all the files based on your folder structure
Set-Location -Path 'c:\shared'
Get-ChildItem -Path 'c:\shared' -Recurse | Where-Object {$_.PSIsContainer $_.LastWriteTime -gt "01-01-1900" -and $_.LastWriteTime -lt (get-date).AddDays(-365) } | ForEach-Object {
$directoryFullName = $_.FullName
$directoryName = $_.Name
Invoke-Expression -Command 'C:\7-Zip\7z.exe a "-x!*.zip" -sdel $directoryFullName\$directoryName.zip $directoryFullName\*'
}
here is the error
At C:\Users\HarrelsonNetworks\Documents\windowspowershell\Scripts\testbackup3.ps1:14 char:75
+ ... Path 'c:\shared' -Recurse | Where-Object {$_.PSIsContainer $_.LastWri ...
+ ~~
Unexpected token '$_' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParseException
FullyQualifiedErrorId : UnexpectedToken
thanks
for your help
jharl
I would suggest the following: 1. Create a temp folder 2. MOVE (not copy) everything you want over to the temp folder 3. Zip the temp forder and save to desired location 3. delete the temp folder.
Breaking it out into steps like this will let you work through the problem better.
Here is something similar I wrote recently, it doesn't solve your problem but it should point you in the right direction:
function archiveLogs ( [string]$OriginalLocation, [string]$NewLocation ){
## Age of files to be archived
$DeleteOlderThan = 30
# Create temp folder to store files to be archived
New-Item c:\Temp\_tempfolder -type directory
# Get all children of specific directory older than 'X' days and of ".log" file type and move to temp folder
get-childitem -Path $OriginalLocation\*.log |
where-object {$_.LastWriteTime -lt (get-date).AddDays(-$DeleteOlderThan)} |
move-item -destination "C:\Temp\_tempfolder"
## Zip all .log files in temp folder and save to '$NewLocation\(DATE)_Archive'
& "C:\temp\7za.exe" a -tzip $NewLocation\$((Get-Date).ToString('yyyy-MM-dd HH-mm'))_Archive -r c:\Temp\_tempfolder\*.log
## Delete temp folder
Remove-Item c:\temp\_tempfolder -recurse -ErrorAction SilentlyContinue
Goodluck and let me know if you have any questions.
You're missing the logical operator -and. To resolve the error, change:
{$_.PSIsContainer $_.LastWriteTime -gt "01-01-1900" -and $_.LastWriteTime -lt (get-date).AddDays(-365) }
To:
{$_.PSIsContainer -and ($_.LastWriteTime -gt "01-01-1900") -and ($_.LastWriteTime -lt (get-date).AddDays(-365)) }

File Sorting Based on Similar File and Folder Names

Im still generally new to powershell, and I am trying to create a program that will take files based on their name, and move them into folders that have a similar name but not exactly the same.
For example, Lets say I have 3 files, Apples.txt, Grapes.txt, and Oranges.txt. And I want to move them into corresponding folders, ApplesUSA, GrapesNY, OrangesFL.
I could just hard code it using a loop and a If-Then Statement. i.e If Apples.txt exists move to ApplesUSA. But I want it to be dynamic, so if other files and folders are added later I dont have to update the code. Is there a way to write a statement that would say if FileA and FolderB are similar in name (both contain apples in the name somewhere) then move fileA to FolderB and so on.
Any help appreciated. Thanks!!!!
try Something like this
$PathWithFile="C:\temp\Test"
$PathWithDir="C:\temp\Test"
Get-ChildItem $PathWithFile -file -Filter "*.txt" | %{
$CurrentFile=$_
$Dirfounded=Get-ChildItem $PathWithDir -Directory | where {$_ -match $CurrentFile.BaseName} | select FullName -First 1
if ($Dirfounded -ne $null)
{
move-Item $CurrentFile.FullName -Destination $Dirfounded.FullName -WhatIf
}
}
A oneliner similar to #Esperento's
gci *.txt -af|%{$File=$_.FullName;gci "$($_.BaseName)*" -ad|%{Move $File -Dest $($_.FullName) -whatif}}
The verbose version:
PushD "X:\path\to\base\folder"
Get-ChildItem *.txt -File | ForEach-Object{
$File = $_.FullName
Get-ChildItem "$($_.BaseName)*" -Directory | ForEach-Object {
Move-Item $File -Destination $_.FullName -whatif
}
}
PopD
Both versions require PowerShell V3 for the -File and -Directory parameters (and their aliases -af/-ad) This can be substituted by an additional |Where-Object{ $_.PSIsContainer} respective | Where-Object{!$_.PSIsContainer}