Getting root folder name with PS - windows

I am trying to create a PowerShell script to fetch the root folder's name where in their subdirectories files with error names are present with today's date. Below is the sample code I have tried so far to pick the folder names.
Root Log folder - C:\Errorlogs, contains many other application log level folders.
$targetDir="C:\Errorlogs"
Get-ChildItem $targetDir -Recurse -ErrorAction SilentlyContinue -Force -Filter "*Error*"|
where {([datetime]::now.Date -eq $_.lastwritetime.Date)} |
select FullName
I have tried the above code; however, it's giving me the whole path as result, whereas I only need the folder name.
Result - C:\Errorlogs\AsyncCreateUsersAPIProcessor\202302\04\Error.txt
Required - AsyncCreateUsersAPIProcessor

Use string LastIndexOf and SubString
$rootPath = "C:\Temp\Errorlogs"
$date = [DateTime]::Now.ToString("yyyyMM\\\\dd")
$pattern = '\\(?<folder>\w+)\\' + $date + '\\Error.*$'
$files = Get-ChildItem -Path $rootPath -Recurse | Select-Object -Property Fullname | Where-Object {$_.Fullname -Match $pattern}
foreach($file in $files)
{
$file.Fullname -match $pattern
Write-Host "folder = " $Matches.folder
}

Looks like you can do it just with splitting the path using \ as delimiter then picking the 3rd token (2nd index of an array):
$targetDir = "C:\Errorlogs"
Get-ChildItem $targetDir -Recurse -ErrorAction SilentlyContinue -Force -Filter "*Error*" |
Where-Object { [datetime]::Now.Date -eq $_.LastWriteTime.Date } |
Select-Object #{ N='Name'; E={ $_.FullName.Split('\')[2] }}
Another option if you want 2 levels up in the folder hierarchy is to query the .Directory property of the file then the .Parent property of the parent folder (2 times or as many times as needed):
$targetDir = "C:\Errorlogs"
Get-ChildItem $targetDir -Recurse -ErrorAction SilentlyContinue -Force -Filter "*Error*" |
Where-Object { [datetime]::Now.Date -eq $_.LastWriteTime.Date } |
Select-Object #{ N='Name'; E={ $_.Directory.Parent.Parent.Name }}

As long as the subfolders inside the folder you are after all have numeric-only names, you can loop backwards to get at the first non-numeric foldername and output that.
$targetDir = "C:\Errorlogs"
Get-ChildItem -Path $targetDir -File -Filter "*Error*" -Recurse -Force -ErrorAction SilentlyContinue |
Where-Object { [datetime]::Now.Date -eq $_.LastWriteTime.Date } | ForEach-Object {
$parentDir = $_.Directory
while ($parentDir.Name -match '^\d+$') { $parentDir = $parentDir.Parent }
$parentDir.Name
}
That way, even a path C:\Errorlogs\AsyncCreateUsersAPIProcessor\202302\02\04\1234\567\Error.txt would produce folder name AsyncCreateUsersAPIProcessor

Related

how to remove directories structures not accessed since a specific date?

how to remove directories structures not accessed since a specific date ?
it might look like something :
Get-ChildItem -Path $path -Recurse -Force -filter IDENTIFY_DIRECTRORY | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | IDENTIFYTHELASTACCCESSTIME | Remove-Item -Force
IDENTIFY_DIRECTORY : I guess it is : -Directory parameter to Get-ChildItem command (select directories only not files)
IDENTIFYTHELASTACCCESSTIME : here I mean check if directory or sub-path/file has been accessed/read since a date I would set from a variable
Final goal of that is to purge useless files from a fileserver to free a maximum of space.
I already did :
Get-ChildItem -Path $path -Recurse -Force -filter *.log | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
maybe workaround
Get-ChildItem -Path "F:\" $_.LastAcessTime -Recurse -Directory -Force -<somemorecommandlineparameters> ......

Powershell command to fetch all file path for all desired files extensions

I want to search all drives using PowerShell on windows machine to get the list of all files along with their extensions -
Based on desired extension we pass in it like - *.mp3 or
Fetch all files with multiple extensions like - *.txt, *.mp3 etc.
I tried below script but its giving only information from where we are running it. But I want to scan whole machine.
Get-ChildItem -Path .\ -Filter ***.doc** -Recurse -File| Sort-Object Length -Descending | ForEach-Object { $_.BaseName }
Checkout the Get-PSDrive cmdlet. It returns a list of drives, and you can specify just disk drives with the -PSProvider FileSystem parameter:
foreach ( $drive in $(Get-PSDrive -PSProvider FileSystem) ) {
Get-ChildItem -Path $drive.Root -Filter ***.doc** -Recurse -File |
Sort-Object Length -Descending |
ForEach-Object { $_.BaseName }
}
Didn't test that but you get the idea.
Using -Include on Get-ChildItem will allow you to specify a list of extensions. The -ErrorAction will cause it to skip drives that are not available such as an unmounted CD drive.
Get-PSDrive -PSProvider FileSystem |
ForEach-Object {
Get-ChildItem -Path $_.Root -Recurse -Include '*.doc*', '*.txt' -ErrorAction SilentlyContinue |
ForEach-Object { $_.Name }
} |
ForEach-Object {[PSCustomObject]#{HashCode = $_.GetHashCode(); FullName = $_.FullName}}
} |
Export-Csv -Path $TempFile -NoTypeInformation -Encoding ASCII
Update:
Here is a better way. It will prevent unknown extensions from getting into the mix such as "Microsoft.NET.Sdk.Publish.Docker.targets."
$ExtensionList = #('.txt', '.doc', '.docx', '.mp3')
$TempFile = Join-Path -path $Env:TEMP -ChildPath "$($pid.ToString()).tmp"
Get-PSDrive -PSProvider FileSystem |
ForEach-Object {
Get-ChildItem -Path $_.Root -Recurse -ErrorAction SilentlyContinue |
Where-Object { $ExtensionList -contains $_.Extension } |
ForEach-Object {
[PSCustomObject]#{
HashCode = $_.GetHashCode();
DirectoryName = $_.DirectoryName
Name = $_.Name
}
}
} |
Export-Csv -Path $TempFile -Delimiter ';' -NoTypeInformation -Encoding ASCII
Write-Host "The temp file is $TempFile"
This is more than what the original question asked, but if you are going to go through the trouble of listing all your files, I suggest getting the filehash as well so you can determine if you have duplicates. A simple file name search will not detect if the same file has been saved with a different name. Adding to what #lit (https://stackoverflow.com/users/447901/lit) has posted:
$ExtensionList = #('.txt', '.doc', '.docx', '.mp3')
Get-PSDrive -PSProvider FileSystem |
ForEach-Object {
Get-ChildItem -Path $_.Root -Recurse -ErrorAction SilentlyContinue |
Where-Object { $ExtensionList -eq $_.Extension } |
## ForEach-Object { $_.Name, $_.FullName, $_.GetHashCode() }
Select-Object #{Name="Name";Expression={$_.Name}}, #{Name="Hash";Expression={$_.GetHashCode()}}, #{Name="FullName";Expression={$_.FullName}} |
Export-Csv -Path C:\Temp\testing.csv -NoTypeInformation -Append
}
The addition of the file hash will allow you to see if you have duplicates and the full name will allow you to see where they are located.

Copy-item in foreach loop based off metadata

In this script I identify the metadata for a group of pictures, then run an if statement inside a foreach loop to copy all pictures from one folder with a certain date to a new directory with that date.
My problem is with Copy-Item, or so I think. If I use the variable $file$ it just places another directory inside the previous directory. The way I have it no just copies all the pictures into that directory despite the if statement that it is contained in.
$fol = "C:"
foreach ($file in $fol) {
$data1 = Get-FileMetaData "C:"
$data2 = $data1 | Select-Object 'Date taken'
if ($data2 -like '*2006*') {
if(!(Test-Path "C:\2006")) {
New-Item -ItemType Directory -Path "C:\2006"
}
Copy-Item "C:\*" "C:\2006"
echo $data2
} else {
echo 'no'
}
}
echo $data2 displays:
why use metatdata for found creation date. You can use creationtime
try this
#if you want move for specific year
$destination="c:\destination\2016"
New-Item -ItemType Directory $destination -Force
Get-ChildItem "c:\temp\" -Recurse -File -Filter "*.png" | Where {$_.CreationTime.Year -eq 2016} | %{Copy-Item $_.FullName "$destination\$($_.Name)" }
#if you want copy all image png by year of creation
$destination="c:\destination"
Get-ChildItem "c:\temp\" -Recurse -File -Filter "*.png" | group {$_.CreationTime.Year} |
%{
$DirYear="$destination\$($_.Name)"
New-Item -ItemType Directory $DirYear -Force
$_.Group | %{Copy-Item $_.FullName "$DirYear\$($_.Name)" }
}
other solution
#explicite version
Get-ChildItem "c:\temp\" -Recurse -File -Filter "*.png" |
ForEach-Object {Copy-Item $_.FullName (New-Item -ItemType Directory "$destination\$($_.CreationTime.Year)" -Force).FullName}
#short version
gci "c:\temp\" -R -File -Fi "*.png" |
% {cpi $_.FullName (ni -I Directory "$destination\$($_.CreationTime.Year)" -Force).FullName}

Moving all folders and subfolders from one drive to another drive using Powershell

Iam using Powershell script to Move folders from one Drive to another.
Here is what i have tried.
Get-ChildItem -Recurse "C:\Personal" | where-object {$_.lastwritetime -gt '5-25-2015'} | foreach {move-item "$($_.FullName)" "D:\Personal"}
This is working if i am moving files within same drive i.e either from cdrive to c drive or d drive to d drive.
But this is not working when iam trying to move from c drive to d drive,...iam getting error like
Move-Item : The file exists.
At line:1 char:113
+ Get-ChildItem -Recurse "C:\Development" | where-object {($_.lastwritetime -lt (get-date))} | foreach {move-item <<<<
"$($_.FullName)" "D:\Development1"}
+ CategoryInfo : WriteError: (C:\Development\test3.txt:FileInfo) [Move-Item], IOException
+ FullyQualifiedErrorId : MoveFileInfoItemIOError,Microsoft.PowerShell.Commands.MoveItemCommand
Please correct me..
What means "this is not working"?
The recurse flag seems to indicate you want to copy a directory structure. This will only work if your target directory already has the same structure as your source. If not, you have to create it along the way. Something like this would work:
function Move-Directories
{
param (
[parameter(Mandatory = $true)] [string] $source,
[parameter(Mandatory = $true)] [string] $destination
)
try
{
Get-ChildItem -Path $source -Recurse -Force |
Where-Object { $_.psIsContainer } |
ForEach-Object { $_.FullName -replace [regex]::Escape($source), $destination } |
ForEach-Object { $null = New-Item -ItemType Container -Path $_ }
Get-ChildItem -Path $source -Recurse -Force |
Where-Object { (-not $_.psIsContainer) -and ($_.lastwritetime -ge (get-date)) } |
Move-Item -Force -Destination { $_.FullName -replace [regex]::Escape($source), $destination }
}
catch
{
Write-Host "$($MyInvocation.InvocationName): $_"
}
}
With a call like this:
Move-Directories "c:\personal" "d:\personal"

How can I use PowerShell to copy the same file to many directories with the same name?

I'm trying to copy one file to any subfolder in a directory that has a specific name. I am part way there, but just can't quite get it to work.
I am able to find all of the subfolders called "help" using:
Get-ChildItem -Path Y:\folder1\subfolder -Directory -Recurse | ? { ($_.PSIsContainer -eq $true) -and ($_.Name -like 'help')}
That will get any folder in Y:\folder1\subfolder named help. So have been trying:
$folder = Get-ChildItem -Path Y:Y:\folder1\subfolder -Directory -Recurse | ? { ($_.PSIsContainer -eq $true) -and ($_.Name -like 'help')}
foreach ($f in $folder){
Copy-Item Y:\Info.html -Destination $folder[$f]
}
and that does not work. Bonus points if you can also tell me how to have it write out to a csv file all of the directories it copies the file to.
Thanks
I wrote this with version 3, but I think it will work with 1 and 2 since I used Set-StrictMode -Version <number> to test them.
The CSV output will look something like this for every line: Y:\Info.html,Y:\folder1\subfolder\help
$logpath = 'C:\log.csv'
$logopts = #{filepath=$logpath; append=$true; encoding='ascii'}
$file = 'Y:\Info.html'
$path = 'Y:\folder1\subfolder'
$search = 'help'
gci $path -d -s `
| ?{ $_.psIsContainer -and $_.name -match $search } `
| %{
cp $file $_.fullName; # copy file
$line = $file, $_.fullName -join ','; # build output
$line | out-file #logopts; # write output
}
Version 1
$folders = #(
(gci Y:\folder1\subfolder -dir -r | ? {$_.Name -like 'help'}).fullname
)
ForEach ($f in $folders) {
Copy-Item Y:\Info.html $f
}
Version 2
(gci Y:\folder1\subfolder -dir -r | ? {$_.Name -like 'help'}).fullname | % {cp Y:\Info.html $_}

Resources