PS script copy new files - windows

Pretty noob at writing PS scripts - wrote this up and have been actively using it although still requires some manual intervention trying to achieve my goal, which I would like to automate completely.
I will try my best to explain clearly;
I am trying to copy '.bak' files to a specific directory from a source folder that has files dropped in it on a daily basis. Problem is the way I created the script, every time it runs it creates a new folder with some of the same files as previously copied.
The files being copied all follow the same name structure in date sequence;
xxxx_2018_01_01_2131231.bak
xxxx_2018_01_02_2133212.bak
xxxx_2018_01_03_2199531.bak
How could I write the script so that it copies newer files only and not what has already been copied previously?
It would also be nice to only create a new folder then a certain part of the file name changes.
Here is the script;
$basedir = "Path:\path"
$today = (Get-Date).ToString('MM_dd_yy')
$Filter = '*.bak'
$location = New-Item -Path $basedir -Type Directory -Name $today
Copy-Item -Path 'Path:\path' -Destination $location -Filter $Filter -Recurse
Any pointers are greatly appreciated!
Thanks in advance for your help!

I'm not sure if there is an easy way to code this, but the general answer would be using the Get-ChildItem cmdlet.
"The Get-ChildItem cmdlet gets the items in one or more specified locations. If the item is a container, it gets the items inside the container, known as child items. You can use the -Recurse parameter to get items in all child containers and use the -Depth parameter to limit the number of levels to recurse."
By using the Get-ChildItem, you could get the listing of files that are in both directories, and then compare them to see if they have the same name. Then build an if() argument based on criteria you wish to use to compare them.
It's not the complete answer, but it is a good starting point.

Thanks everyone for pitching in, much appreciated!
I have switched over to the batch file route and have created the following to accomplish my goal;
#echo off
setlocal
set _source="C:\users\user1\desktop\source"
set _dest="C:\users\user1\desktop\dest"
robocopy %_source% %_dest% *.bak /mir /XC /XN /XO
Any opinion on this script is encouraged!

Related

How to use short-cut paths to Compress-Archive to zip current folder into same destination

I am using Compress-Archive and want to zip the current directory into the same path. However I do not want to have to type out the entire file path both times. Is there an easy way to do this?
I am using windows 10 pro.
This works for the most part Compress-Archive . test.zip but I want it to be on the same level as the current directory so I need to put it back one spot.
Something like this is what I want:
path/test
path/test.zip
What I am getting:
path/test
path/test/test.zip
It is going inside the actual folder which is not what I want
You propably want that:
Compress-Archive * ..\test.zip
The wildcard * avoids that the name of the folder is put inside the zip.
Using .. for the output path we go one level up in the directory tree.
This command will fail if test.zip already exists. Either add parameter -update to update the archive or add -force to overwrite the archive. Both can be used even if the archive does not already exist.
If the current working directory is "t", it can be included using the following command. I would note that I do not think putting the destination .zip file in the directory being compressed is a good idea.
Compress-Archive -Path $(Get-ChildItem -Recurse -Exclude t.zip) -DestinationPath .\t.zip -Force
It is shorter if you are willing to use aliases and cryptic switches.
Compress-Archive $(gci -r -e t.zip) .\t.zip -Force
If I have misinterpreted your situation, please leave a comment or improve the information provided by editing the question.

How to search through folders for a certain file using Powershell

I am writing an uninstall script for Office using Powershell. I need the script to search through:
C:\windows\ccmcache\
There are a number of folders in there. Is there a way to find which folder has the contents that I am looking for? So let's say I am looking for a folder that contains:
office.en-us
office64.en-us
and so on. How can I return that exact path? Because that is where I am running the uninstall from but the catch is I don't know what folder Office is in the ccmcahce folder.
Thank you all in advance.
No loop needed.
dir "C:\windows\ccmcache\*\Office.en-us" -Directory
Note that dir is an alias for Get-ChildItem.
#Tomalak when running the code you posted it works if there aren't a large number of files and folders to sort through, but if you really have no idea where the file or folder you're looking for lives at then specifying a -recurse parameter would be helpful
Get-Childitem "C:\*\Office.en-us" -Recurse
While this is sometimes necessary (in this case it doesn't seem to be), it can take an extended amount of time to run if there are large folders to sort through...

How to step backwards in a path using Powershell

I am searching through folders in order to find the one that has the contents that I desire.
$path = dir "C:\windows\ccmcache\*\Office.en-us" -Directory
echo $path
It returns:
Directory: C:\windows\ccmcache\c
But when I run my command:
Start-Process "$path\setup.exe /uninstall ProPlus /config Uninstall.xml" -Wait
It tries to run:
C:\windows\ccmcache\c\Office.en-us\setup.exe............
Which doesn't exist! So how can I go back a step so I can run the setup.exe command out of the c folder?
Something like:
$path2 = $path\cd..
Thank you all in advance.
You can simply do:
$Path2 = Resolve-Path (Join-Path $Path '..')
Note:
Join-Path is the cross platform way of concatenating path strings
Resolve-Path will give you a fully qualified path name
^^ step is optional, since windows will traverse the .. for you, but it helps to visually see the folder it resolves to.
Does this help?
You are using Get-ChildItem to return a System.IO.DirectoryInfo object. The path you are looking for already exists there as the Parent property.
$path2 = $path.Parent.FullName
No other cmdlets are needed here. You don't even need to save it into another variable if you don't want to.
Beware that your $path could have multiple results which will have consequences later in your code. If you only cared about the first one you could add | Select -First 1 to guarantee only one result.
It can be done simply using Resolve-Path function.
suppose structure is like following
root
Folder1 Folder2
and our current working directory is Folder1 and we want to move to Folder2.
$path2 = Resolve-Path("$path\..\Folder2\fileinFolder2")
I'm not sure I completely understand what you're asking.. Do you mean how to backtrack in your file directory? That command is "cd .."
Do you mean how to call $path THEN move one level higher in the directory? If so you'll need to create a new $var that is one level higher before calling your setup.exe

Evaluating Variables first in PowerShell Commands

I'm trying to get PowerShell to evaluate variables before executing a command, for example:
$OutputPath = "C:\Temp"
Get-ChildItem -include *.mp3 | Move-Item -Destination $OutputPath
However, the Move-Item cmdlet tries to interpret this literally, so it doesn't get moved. The script works fine whenever I enter the path directly, but I need to be able to control the path with a variable. How do I do this?
This answer could evolve but as your question stands I see a big issue that is unfortunately poorly documented. -Include and -Exclude only perform their intended functions when partnered with -Recurse. Used without it can yeild 0 results. In your case that would mean nothing is passed through the pipe and Move-Item is not executed.
Currently you are just filtering on *.mp3 which is basic and can just be used with the -filter parameter. While you don't need to I would recommended specifying -Path as well so that you move the files you wanted.
Get-ChildItem -Filter *.mp3 | Other-Stuff ...
You mentioned in comments the following error:
Move-Item : Cannot create a file when that file already exists.
That error is very specific. Either from previous testing or an oversight in new names that file indeed already exists. Two things you can do to help with that problem is use the -WhatIf switch which should quote a file path on the verbose stream so you know where the file would end up.
Second, if you understand the data risk, is to use -Force so that the file will be overwritten by the new one. With Copy-Item it is not a big deal since the original file still exists. Mistakes with Move-Item can be permanent.

Powershell find and replace not recursing through sub-directories

I would like to recurse through all subfolders of a given folder, and for all files of a given extension (optionally wildcard), search and replace some piece of text.
There's a similar previous question here, and I'm trying to get a modified version of the top answer working for my purpose. It uses Powershell for the find and replace. However, my modified version below is not recursing. I don't remember where I found the recurse part of the first line, so maybe I'm using that incorrectly.
Get-ChildItem *.* -exclude *.ps1* -recurse |
Foreach-Object {
$c = ($_ | Get-Content)
$c = $c -replace 'foo','bar'
[IO.File]::WriteAllText($_.FullName, ($c -join "`r`n"))
}
I am running the code from the Powershell command line as a PS batch file, .ps1, hence the exclusion of that extension.
This works fine if I run it directly in a folder that has some files I want searched, but if I run it from a parent of that folder, the searching/ recursion of subfolders does not happen. It doesn't even try to, which I can tell from the fact that the command finishes running instantaneously. If I run it in my first subfolder, which has about 50 text files, there's a couple seconds delay before it finishes, indicating to me it's actually searching those files.
I've also tried this with the exclude portion removed and the behaviour is the same.
My guess is that *.* matches only items with a dot in them. Folders have no extension, so they aren't matched.
gci -rec -force -exclude *.ps1 | should do what you want.

Resources