I like to know how to get 5J91Q4CX.C10 to use in a variable.
C:\Users\user\AppData\Local\Apps\2.0\5J91Q4CX.C10
On all user profiles this folder has a different name.
It is always 8 numbers and digits then a . and then 3 digits or numbers.
I need to use this for a powershell script.
Any idea how I can make a variable for this foldername?
Thanks
I'd do something like this:
#Loop through all user profile folders using something like this:
$userFolders = Get-ChildItem -Path "C:\Users\" -Directory -Force -ErrorAction SilentlyContinue |
Where-Object { #('All Users','Default User', 'Public', 'Default') -notcontains $_.Name } |
Select-Object -ExpandProperty Name
# next loop through these folders to find the foldername that can be different for each user
foreach ($userName in $userFolders) {
$folderName = Get-ChildItem -Path "C:\Users\$userName\AppData\Local\Apps\2.0" -Directory -Force -ErrorAction SilentlyContinue |
Where-Object { $_.Name -match '[A-Za-z0-9]{8}\.[A-Za-z0-9]{3}' } |
Select-Object -ExpandProperty Name
# do something with this variable
Write-Host "C:\Users\$userName\AppData\Local\Apps\2.0\$folderName"
}
Some RegEx could do the trick:
$str = "C:\Users\user\AppData\Local\Apps\2.0\5J91Q4CX.C10"
$str -match '.*\\(.*)$'
$matches[1] # 5J91Q4CX.C10
.*\\(.*)$ matches all chars after the last dash \ and before the end of the line $
not sure what you are really trying to do... you could do a directory search through the C:\Users to report back on all subfolders and then a Foreach loop to go through each subfolder and create the file wanted in the destination etc, something like:
$FOLDERS = Get-ChildItem C:\Users -Directory
FOREACH ($FOLDER in $FOLDERS) {
#WHATEVER YOU WANT TO DO
}
Related
I'm trying to modify a PS script so that it can:
A: Check that multiple files exist and are dated today
B: Do this from multiple locations
$folder = '\\path\subfolder\'
$files = #(
"file1.txt",
"file2.txt",
"file3.txt",
)
Write-Host "Folder: $folder."
# Get only files and only their names
$folderFiles = Get-ChildItem -Path $folder -Recurse -File -Name
foreach ($f in $files) {
if ($folderFiles -contains $f) {
Write-Host "File $f was found." -foregroundcolor green
} else {
Write-Host "File $f was not found!" -foregroundcolor red
}
}
A the moment this script is designed to only look in one folder and not check for files only dated today. I have no clue how to change it to use multiple folder locations.
I guess what you are looking for is something like this:
# create an aray of paths to search through
$folders = '\\server1\share\path\subfolder\', '\\server2\share\path\subfolder\'
# create an array of file names to look for
$files = 'file1.txt', 'file2.txt', 'file3.txt'
# get the current date as of midnight
$refDate = (Get-Date).Date
# retrieve objects from recursing through the array of folders
Get-ChildItem -Path $folders -Include $files -File -Recurse |
Where-Object { $_.LastWriteTime -ge $refDate } |
# output whatever properties you want from the files
Select-Object DirectoryName, Name, LastWriteTime
Parameter -Include is only valid when the path ends with \* OR if the -Recurse switch is used
To get items from today, you could do something similar:
Get-Childitem $folder * -Recurse | Where-Object {$_.CreationTime -gt (Get-Date).Date }
As for the multiple locations - I would suggest creating an array of folders you want to search and then iterating through the array.
I am trying to build a PowerShell script that can search for files with similar names inside of a folder.
The files will always have a similar name template:
filename(C).TIF
filename(M).TIF
filename(Y).TIF
filename(K).TIF
All I need to do is to extract the "filename", check if there are 4 similar ones (C,M,Y,K) and use it as a variable to move those files.
$files = Get-ChildItem -Path "E:\test" -Filter "*.TIF" |
Foreach-Object {$_.BaseName} | Sort-Object -Unique
$files = $files -replace ".{3}$"
$names = (Get-Unique -InputObject $files)
$names
The result looks like this:
jobname
jobname
jobname
jobname
test
test
test
test
But I need to sort by unique and count them, maybe, before action.
But I need to sort by unique and count them, maybe, before action.
You definitely want the Group-Object cmdlet!
As the name suggests, it... groups objects, based on some common property:
$filesByCommonBaseName = Get-ChildItem -Path "E:\test" -Filter "*.TIF" |Group-Object { $_.BaseName -replace '.{3}$' }
Now that you have them grouped correctly, you can start operating on them as such:
foreach($entry in $filesByCommonBaseName){
Write-Host "Operating on files starting with $($entry.Name)"
if($entry.Count -eq 4){
# we found four matches, move them!
$entry.Group |Move-Item -Destination $destinationDir -Force
}
}
Hello awesome community :)
I have a list containing a bunch of SKU's. All the filenames of the files, that I need to copy to a new location, starts with the corresponding SKU like so
B6BC004-022_10_300_f.jpg
In this case "B6BC004" is the SKU and my txt list contains "B6BC004" along with many other SKU's.
Somewhere in the code below I know I have to define that it should search for files beginning with the SKU's from the txt file but I have no idea how to define it.
Get-Content .\photostocopy.txt | Foreach-Object { copy-item -Path $_ -Destination "Z:\Photosdestination\"}
Thanks in advance :)
If all files start with one of the SKU's, followed by a dash like in your example, this should work:
$sourceFolder = 'ENTER THE PATH WHERE THE FILES TO COPY ARE'
$destination = 'Z:\Photosdestination'
# get an array of all SKU's
$sku = Get-Content .\photostocopy.txt | Select-Object -Unique
# loop through the list of files in the source folder and copy all that have a name beginning with one of the SKU's
Get-ChildItem -Path $sourceFolder -File -Recurse |
Where-Object { $sku -contains ($_.Name -split '\s*-')[0] } |
ForEach-Object { $_ | Copy-Item -Destination $destination }
I haven't tested this so please proceed with caution!
What is does it loops through all the items in your photostocopy.txt file, searches the $source location for a file(s) with a name like the current item from your file. It then checks if any were found before outputting something to the console and possibly moving the file(s).
$source = '#PATH_TO_SOURCE'
$destination = '#PATH_TO_DESTINATION'
$photosToCopy = Get-Content -Path '#PATH_TO_TXT_FILE'
$photosToCopy | ForEach-Object{
$filesToCopy = Get-ChildItem -Path $source -File | Where-Object {$_.Name -like "$_*"}
if ($fileToCopy.Count -le 0){
Write-Host "No files could be found for: " $_
}else{
$filesToCopy | ForEach-Object{
Write-Host "Moving: " $_.Name
Copy-Item -Path $_.FullName -Destination $destination
}
}
}
Let me know how if this helps you :)
I'm using PowerShell command prompt and I want to set a location to the folder "Folder". The thing is that folder can be everywhere.
I've tried the command Set-Location and Resolve-Path but I don't get it.
I want to do something like that:
$path = Resolve-Path ".*/Folder"
Set-Location $path
Where the .* can be all the parent folder
Any idea?
Would try this:
Get-ChildItem -Path .\ -Name Folder -Recurse -Depth 10
Hope it helps. BR
Edit (see comments):
$array = Get-ChildItem -Path .\ -Name Ping -Recurse -Depth 10
if($array.Count -eq 0){
#stay
}
if($array.Count -eq 1){
Set-Location $array
}
else{
$array | ForEach-Object{Write-Host $_}
}
Requires PowerShell v3 or higher, you can check using $PSVersionTable.*
$path = (Get-ChildItem . -Recurse -Directory | Where-Object { $_.Name -eq "Folder" }).FullName
This will give you all the directories named Folder in current directory and its subdirectories recursively.
The query, however, can return multiple results so if you want to choose the first one use [0]. Also, to cover the case when the query returns no results, enforce returned object to be an array using #( ... ) and check if it exists:
$f = #(Get-ChildItem . -Recurse -Directory | Where-Object { $_.Name -eq "Folder" })[0].FullName
if ( $f ) {
cd $f
}
else {
# Handle the error
}
cd is alias to Set-Location so you can use whichever you prefer. Important thing to remember is to use FullName property as it contains full path to the folder.
* For PowerShell versions lower than v3, use | Where-Object {$_.PSIsContainer -eq $true} instead of -Directory
I have this PowerShell code that compares 2 directories and removes files if the files no longer exist in the source directory.
For example say I have Folder 1 & Folder 2. I want to compare Folder 1 with Folder 2, If a file doesn't exist anymore in Folder 1 it will remove it from Folder 2.
this code works ok but I have a problem where it also picks up file differences on the date/time. I only want it to pick up a difference if the file doesn't exist anymore in Folder 1.
Compare-Object $source $destination -Property Name -PassThru | Where-Object {$_.SideIndicator -eq "=>"} | % {
if(-not $_.FullName.PSIsContainer) {
UPDATE-LOG "File: $($_.FullName) has been removed from source"
Remove-Item -Path $_.FullName -Force -ErrorAction SilentlyContinue
}
}
Is there an extra Where-Object {$file1 <> $file2} or something like that.?
I am not sure how you are getting the information for $source and $destination I am assuming you are using Get-ChildItem
What i would do to eliminate the issue with date/time would be to not capture it in these variables. For Example:
$source = Get-ChildItem C:\temp\Folder1 -Recurse | select -ExpandProperty FullName
$destination = Get-ChildItem C:\temp\Folder2 -Recurse | select -ExpandProperty FullName
By doing this you only get the FullName Property for each object that is a child item not the date/time.
You would need to change some of the script after doing this for it to still work.
If I am not getting it wrong, the issue is your code is deleting the file with different time-stamp as compared to source:
Did you try -ExcludeProperty?
$source = Get-ChildItem "E:\New folder" -Recurse | select -ExcludeProperty Date
The following script can serve your purpose
$Item1=Get-ChildItem 'SourcePath'
$Item2=Get-ChildItem 'DestinationPath'
$DifferenceItem=Compare-Object $Item1 $Item2
$ItemToBeDeleted=$DifferenceItem | where {$_.SideIndicator -eq "=>" }
foreach ($item in $ItemToBeDeleted)
{
$FullPath=$item.InputObject.FullName
Remove-Item $FullPath -Force
}
Try something like this
In PowerShell V5:
$yourdir1="c:\temp"
$yourdir2="c:\temp2"
$filesnamedir1=(gci $yourdir1 -file).Name
gci $yourdir2 -file | where Name -notin $filesnamedir1| remove-item
In old PowerShell:
$yourdir1="c:\temp"
$yourdir2="c:\temp2"
$filesnamedir1=(gci $yourdir1 | where {$_.psiscontainer -eq $false}).Name
gci $yourdir2 | where {$_.psiscontainer -eq $false -and $_.Name -notin $filesnamedir1} | remove-item
If you want to compare files in multiple dir, use the -recurse option for every gci command.