list contents with batch - batch-file

I need a bat file that will list the entire contents of a folder Including its subfolders in a text file.
one of our programs seams to constantly be missing or adding files. a list would help me trackdown the issue(s).

Wouldn't this do it?
dir C:\autocad /s /b > output.txt

If you have PowerShell, you can use this instead:
cd *<targetdirectory>*
ls -r |% { $_.FullName } | Set-Content foldercontents.txt
I only bring it up, because you can then compare the next time you check to see differences:
$original = Get-Content foldercontents.txt;
$now = ls -r |% { $_.FullName }
Write-Host "Missing Files:";
$original |? { -not $($now -contains $_) };
Write-Host "Added Files:";
$now |? { -not $($original -contains $_) };

If your problem is just tracking down what is the program that is creating and removing files, you may monitor all the file accesses in the system with Sysinternals Process Monitor http://technet.microsoft.com/en-us/sysinternals/bb896645 . An easy way to watch all the file accesses being done by any process.

Related

How to move only specific files in cmd to another folder?

I have a folder with files of different naming patterns. For example:
S012344
S00abcd
DA01234
DAL1230
D13459A
MOV0001
M123004
Now I need to move all the files except the one which have the following naming patterns: (** means regular expression)
- S00****
- Starts with D and ends with A
- MOV****
I need to do this as part of a batch file, I searched a lot but didn't find any apt solutions to address this problem.
There are ambiguities in your question. But, here is a possible way to do it. If you are on a supported Windows system, then it will have PowerShell. When you are satisfied that the files will be moved correctly, remove the -WhatIf from the Move-Item command.
=== Move-FilesIWant.ps1
Get-ChildItem -File -Path 'C:\src\t\' |
Where-Object { $_.BaseName -notmatch '(^S00....$|^D.*A$|^MOV....$)' } |
ForEach-Object { Move-Item -Path $_.FullName -Destination 'C:\new\dir' -WhatIf }
If you must run it from a cmd.exe shell or .bat file script, use:
powershell -NoLogo -NoProfile -File '.\Move-FilesIWant.ps1'

Powershell Looping issue with process before next loop

I am new to Powershell and I am having an issue within a loop that I need assistance with. I am attempting to rename some files that are created as part of the process within the loop.
I have tested the code OUTSIDE of the loop and it works fine. However, when I try to put it in the loop, nothing seems to happen.
The files I need to rename are in the following locations…
(1)“\MYSERVER\MYCOMPANY\MYFOLDER\ MyPrintouts\EstimateImport\ImportPrintout.txt”
(2)“\MYSERVER\MYCOMPANY\MYFOLDER\ MyPrintouts\PostEntries\ImportPostEntries.txt”
I need to tack the date and time on the end. This code works for me OUTSIDE of the loop. I put it in a file I named RenameFiles.ps1
#File location
$ImportPrintout = “\\MYSERVER\MYCOMPANY\MYFOLDER\MyPrintouts\EstimateImport\ImportPrintout.txt”
$ImportPostEntries = “\MYSERVER\MYCOMPANY\MYFOLDER\ MyPrintouts\PostEntries\ImportPostEntries.txt”
#Find and rename the import printouts
Get-ChildItem $ImportPrintout -Filter "ImportPrintout.txt" | ForEach-Object {
Rename-Item $_.FullName "$BackupFolder$($_.BaseName -replace " ", "_" -replace '\..*?$')$(Get-Date -Format "MMddyyyy-HHmmss").txt"}
Get-ChildItem $ImportPostEntries -Filter "ImportPostEntires.txt" | ForEach-Object {
Rename-Item $_.FullName "$BackupFolder$($_.BaseName -replace " ", "_" -replace '\..*?$')$(Get-Date -Format "MMddyyyy-HHmmss").txt"}
This is how I added it to the loop as I want the files renamed BEFORE the next file is processed…
#Define actions after an Event is Detected
$action = {$files = Get-ChildItem -Path $watcher.Path -Filter $watcher.Filter #-Recurse
foreach ($file in $files)
{
#Define variables for log file
$changeType = $Event.SourceEventArgs.ChangeType #Your event trigger "Created"
$fileDate = $file.LastWriteTime #Date/Time Estimate was created
#logline contains = Date/Time of import, Created, Date/Time Created, filename
$logline = "$(Get-Date), $changeType, $fileDate, $file"
#Actions to take ==============================================================
#Write details to the log
Add-Content "“\\MYSERVER\MYCOMPANY\MYFOLDER\EstimateImportLog.txt" -value $logline
#Copy the estimate to the "ToBeProcessed" folder
Copy-Item $file.FullName -Destination $copyTo
#Move the estimate to the "EstimateHistory" folder
Move-Item $file.FullName -Destination $moveTo -Force
#Run the powershell script that launches the .bat file that launches the macro
Invoke-Expression "& '\\MYSERVER\MYCOMPANY\MYFOLDER\PSscriptToRunBATfile.ps1'"
#Pause the script for 30 seconds to allow the estimate to finish posting
Start-Sleep -Seconds 30
Invoke-Expression "& '“\\MYSERVER\MYCOMPANY\MYFOLDER\RenameFiles.ps1'"
}
}
This seems to “break” my loop. However, I need this to be done BEFORE going to the next file. How can I accomplish renaming these files before moving on. Any assistance would be greatly appreciated. Thank you!
As far as the loop failing, you're probably encountering an error. Either set your $ErrorActionPreference to Continue or set it to Stop and wrap try/catch blocks around your copy-item and move-item to detect and handle errors.
That probably also addresses the failure of the copy-item/move-item to change the file name, it's running into an error trying to perform that action and failing.

Rename files in Powershell deleting everything after "_"

I am renaming several hundred files, all which vary with an item ID and then a bunch of text after. For example...
BBAT300_abcdefg.xls
BBAT400_abcdefg.xls
I need to delete everything from the underscore, and including the underscore on, so the result is this:
BBAT300.xls
BBAT400.xls
I found this bit of code earlier...
Get-ChildItem -Name -Filter *.xls | foreach {[Regex]::Match($_,"^[^_]*").Value}
and it appears to work, but I can't get it to actually rename the files. My knowledge of scripting is little to none, so this may be an easy fix, I just can't seem to find it. Powershell will show the results in powershell, but not actually rename the files.
You can just pipe this line to the rename item command:
Get-ChildItem -Filter *.txt | Foreach-Object -Process {
$NewName = [Regex]::Match($_.Name,"^[^_]*").Value + '.txt'
$_ | Rename-Item -NewName $NewName
}
EDIT: Changed it to support any location

Powershell: ForEach only looping once?

I have a script that I've been working on, which reads a specified directory, locates .CSV files, and executes some logic for each of the .CSV files and ultimately renames them .csv.archived .
The code was working fine last night, however this morning, when I execute the code it only loops through once. For example, last night, I had 5 .csv files in the directory, it would return the file names for all 5 files in a single action. Now, each time I execute my script, it grabs the first file, performs the actions intended, and then exits forcing me to manually initiate the script for each file.
I've gutted the irrelevant code for testing purposes, and would be happy if someone could tell me that I am doing something wrong, and that I am not crazy.
Here's the code:
$iterations = 1
#set the location where the .CSV files will be pulled from
$Filecsv = get-childitem "\\SERVERPATH\Audit Test\" -recurse | where {$_.extension -eq ".csv"} | % {
$filename = $_.Name
}
#for each file found in the directory
ForEach ($Item in $Filecsv) {
#spit out the file name
"File Name: " + $filename
#count the times we've looped through
"Iterations : " + $iterations
# get the date and time from the system
$datetime = get-date -f MMddyy-hhmmtt
# rename the file
rename-item -path ("\\SERVERPATH\Audit Test\"+ $filename) -newname ($filename + $datetime + ".csv.archived")
$iterations ++
}
...and here is the Output:
For the example I showed you, I had four .CSV files in the directory. I had to manually execute my script, and each time it would perform as expected, but only for the first item it encounters in the directory. It doesn't actually loop through, what am I missing here?
Right here (folded at the pipe for readability):
$Filecsv = get-childitem "\\SERVERPATH\Audit Test\" -recurse |
where {$_.extension -eq ".csv"} |
% {$filename = $_.Name}
You're looping through your files and for each one setting $filename to the name of that file instead of letting the filenames accumulate in $Filecsv
$Filecsv = get-childitem "\\SERVERPATH\Audit Test\" -recurse |
where {$_.extension -eq ".csv"} |
% {$_.Name}

Script to recursively remove specific file from child paths?

I've tried searching for this answer for awhile now, but can't seem to find what I'm after. Perhaps I'm wording it strangely.
I need a script that will recursively delete a specific file from each child directory in a network share.
For example:
\\\share\\*\a\b\file.settings
The * represents n number of child directories. The rest of the path will always be the same. It seems like I might be able to do this with a combination of Get-childitem and remove-item in Powershell, but I'm having trouble working out the exact command I need.
Any help would be immensely appreciated! Thanks.
Something like this should work:
Get-ChildItem '\\server\share' -Recurse | ? {
$_.FullName -like '*\a\b\file.settings'
} | Remove-Item
If you're just interested in files .\a\b\file.settings in the immediate child folders of \\server\share you could simplify the code to something like this:
Get-ChildItem '\\server\share\*\a\b\file.settings' | Remove-Item
Breaking out my comment code into long form:
$folders = Get-ChildItem "\\server\share\" -Directory
ForEach ($folder in $folders) {
$file = Join-Path $folder.FullName "\a\b\file.settings"
if (Test-Path $file) { Remove-Item $file }
}
While I wasn't able to get this to work with Powershell, the below VBS I put together does seem to work well:
Set FSfolder = FSO.GetFolder(\\server\share)
For Each subfolder In FSfolder.SubFolders
UserProfile=subfolder.Name
SettingFile="\\server\share\" & UserProfile & "\a\b\file.settings"
If FSO.FileExists(SettingFile) Then
FSO.DeleteFile(SettingFile)
End If
Next

Resources