Is there a correct form of using find? - powershell

I am trying to delete everything except init.py, using this command in powershell(windows 10 and python django version- 2.2.7):
find . -path "/blog/migrations/.py" -not -name "init.py" -delete
Tree of this project(attaching image)
**If i run the command i am getting this error:
FIND: Parameter format not correct
What to do? Thank you in advance. I am new to python django.**

The following script will delete all files that aren't named "init.py". Make sure to run this at the root of the folder you would like to delete items from.
Get-Childitem -File -Recurse | Where-Object{$_.Name -ne "init.py"} | Remove-Item -WhatIf
To test, leave the -WhatIf switch. If it displays the files you would like to remove, run again without the -WhatIf switch.

Related

How to prevent PowerShell -Recurse from renaming first file twice?

When using powershell to rename files with their directory name and file name, my code works, except in the first file in a directory, it gives it two copies of the directory name. So the file book1.xlsx in folder folder1 should become folder1book1.xlsx but it becomes folder1folder1book1.xlsx. The remaining files in folder1 are correctly named folder1book2.xlsx, folder1book3.xlsx, etc.
I have a directory, with many sub-directories. In each sub-dir are files that need their sub-dir name added in.
I've been following this code. For me it looks like:
dir -Filter *.xlsx -Recurse | Rename-Item -NewName {$_.Directory.Name + "_" + $_.Name}
I've also tried
--setting the Recurse -Depth 1 so that it doesn't keep looking for folders in the sub-folders.
--using ForEach-Object {$_ | ... after the pipe, similar to this.
--running it in Visual Studio Code rather than directly in PowerShell, which turns it into:
Get-ChildItem "C:\my\dir\here" -Filter *.xls -Recurse | Rename-Item -NewName {$_.DirectoryName + '_' + $_.Name}
--putting an empty folder inside the sub-directory, setting -Depth 2 to see if that will "catch" the recurse loop
I would expect the files to be named folder1_book1.xlsx, folder1_book2.xlsx, folder1_book3.xlsx.
But all of the attempted changes above give the same result. The first file is named folder1_folder1_book1.xlsx [INCORRECT], folder1_book2.xlsx[CORRECT], folder1_book3.xlsx[CORRECT].
A workaround might be writing an if statement for "not files that contain the sub-directory name" as suggested here. But the link searches for a text string not an object (probably not the correct term) like #_.Directory.Name. This post shows how to concatenate objects but not something like #_.Directory.Name. Having to put in an if statement seems like an unnecessary step if -Recurse worked the way it should, so I'm not sure this workaround gets at the heart of the issue.
I'm running windows 10 with bootcamp on a 2018 iMac (I'm in Windows a lot because I use ArcMap). Powershell 5.1.17134.858. Visual Studio Code 1.38.0. This is a task I would like to learn how to use more in the future, so explanations will help. I'm new to using PowerShell. Thanks in advance!
This was a script I created for one of my customers that may help
<##################################################################################################################################
This script can be used to search through folders to rename files from their
original name to "filename_foldername.extension". To use this script
please configure the items listed below.
Items to Congfigure
-$Original
-$Source
-$Destination
-$Files
Also please change the Out-File date on line 29 to today's date ****Example: 2019-10-02****
We've also added a change log file that is named "FileChange.txt" and can be found in the location identified on line 30
>
$Original="C:\temp\test" #Location of ".cab" files copied
$Source="C:\temp\Test" #Location were ".cab" files are stored
$Destination="C:\temp\Test\2019-10-02" #Location were you want to copy ".cab" files after the file name change. Be sure to change the date to the date you run this script. The script creates a folder with todays date
$Files=#("*.cab") #Choose the file type you want to search for
$ErrorActionPreference = "SilentlyContinue" #Suppress Errors
Get-ChildItem $Original -Include "*.cab" -File -Recurse | Rename-Item -NewName {$_.BaseName+"_"+$_.Directory.Name +'.cab'}
New-Item -ItemType Directory -Path ".\$((Get-Date).ToString('yyyy-MM-dd'))"; Get-ChildItem -recurse ($Source) -include ($Files) | Copy-Item -Destination ($Destination) -EA SilentlyContinue
Get-ChildItem $Original | Where {$_.LastWriteTime -ge [datetime]::Now.AddMinutes(-10)} | Out-File C:\temp\test\2019-10-02\FileChange.txt

Delete multiple files using powershell and a .txt file

I have a .txt with the names of over 1000 files I want to delete. My .txt file does not have file paths. The files I want to delete are spread throughout multiple folders but they are all in the same drive. Is there any way to use powershell or command prompt to search for all files within my drive with the same name as what is listed in my .txt file and delete them?
Assuming you're PowerShell prompt is currently set at the root location from which you want to start your search and the file is in the same directory:
gc .\MyListOfFilesIWantToDelete.txt | %{gci $_ -Recurse | Remove-Item -WhatIf}
Note, you'll have to remove the -whatif
Or, let's say your file is somewhere else where you have PowerShell opened (eg: ~/Documents), and you want to scan your D: drive. This should work:
gc .\MyListOfFilesIWantToDelete.txt | %{gci D:\ -Filter $_ -Recurse -ErrorAction SilentlyContinue | Remove-Item -WhatIf}
Note I put SilentlyContinue. This is because you'll see a lot of red if you don't have access to folders in your search path.
Alternatively, you can load up a variable with your list of files..
$thesefiles = gc .\mylistoffilesiwanttodelete.txt
.. and use the Remove-Item cmdlet directly..
Remove-Item -Path D:\Folder -Include $thesefiles -Recurse -WhatIf
or in one swoop without loading a variable:
Remove-Item -Path D:\Folder -Include $(gc .\mylistoffilesiwanttodelete.txt) -Recurse -WhatIf
Again, I'm using -WhatIf for testing. Also, I've noticed different behaviors in the past with get-childitem on different versions of PowerShell. I tested these with 5.1
Change directory from following powershell command
Following command will allow you to delete .txt files in specific directory
Get-ChildItem C:\*.txt -file -r | remove-item

How can I delete all of the contents of a directory (including subdirectories) except one subdirectory?

I'm trying to write an automated build and deploy script using PowerShell 2 for my angular2 app, but seeing as how our ASP.NET Web API lives in api/, I want to delete all of the old angular code without touching the API.
Here's what I've got so far:
Get-ChildItem -Path $destination -Recurse -exclude somefile.txt |
Select -ExpandProperty FullName |
Where {$_ -notlike $destination+'\api*'} |
sort length -Descending |
Remove-Item -force -recurse
$destination is the directory where the app gets installed.
Quick folder tree in case I wasn't clear above:
$destination
api\
app\
assets\
vendor\
index.html
main.js
system-config.js
As above, I want to delete everything but api\
I don’t have access to PowerShell 2. But, using PowerShell 3 (and later versions), you should be able to simplify your code by using something like this:
$path = "C:\test path"
Remove-Item $path -recurse -Exclude "api"
I created the same folder structure you specified assuming that api, app, assets, and vendor are sub-folders. I ran the script in the PowerShell IDE and it removed everything under the test path except for the api folder. I would assume that PowerShell 2 supports the same parameters on the command.

Log what is deleted

I'm very new to this but I have a problem with deleting 30days old files which I found an answer to here: Powershell - Delete subfolder(s) in folder with specific name(s) older than 30 days
But I would like to make a follow question on that.
The code I use is this:
gci P:\ -directory -recurse | ?{$_.FullName -match ".:\\.+?\\.+?\\.+?\\.+?\\.+?\\" -and $_.CreationTime -lt (get-date).AddDays(-30)}|Remove-Item -recurse -whatif
Is it possible to log what is deleted as well? Would be awesome if the size of the files are included in the log file. Thanks!
Make the remove operation verbose and redirect the verbose stream to a file:
... | Remove-Item -Recurse -Verbose 4> 'C:\path\to\your.log'
Note that this requires at least PowerShell v3.
If you only want to log what would be deleted without actually deleting it, use -WhatIf instead of -Verbose:
... | Remove-Item -Recurse -WhatIf
You can also combine the two:
$dryrun = $true # set to $false to actually delete
... | Remove-Item -Recurse -Verbose -WhatIf:$dryrun 4> 'C:\path\to\your.log'
However, -WhatIf output goes to the host console, so it can't be redirected to a file. You could use Start-Transcript as a workaround, but that would record everything, not just the would-be deletes. Or you could run the entire code/script (without redirections) in a new PowerShell process:
powershell.exe -File 'C:\path\to\your.ps1' > 'C:\path\to\your.log'
The host output of a child PowerShell process is merged into its STDOUT, so you can redirect it "from the outside".

Get powershell to display all paths where a certain file can be found on a drive

I'm trying to build a function that will show me all path's where a certain filename is located. The function would take one parameter, that being the file name.
The result would be either a list of all paths, or a message saying there's no such file on the system.
I'm new to Powershell, and I'm not getting the syntax just yet.
I've tried this:
Get-ChildItem -Path -Include notepad.exe
But that threw an error message. I'm currently trying:
$i="notepad.exe"
Foreach ($i in Get-ChildItem c:\ -Recurse){echo -Path}
Started that now, it's still running, don't know what'll happen, really.
EDIT: echo'd an enormous amount of lines that just say "-Path"...
Can anybody help with this problem? I'm running Powershell 1.0 by the way.
So, to explain what I wish to see when executing this command, here is an example of what I expect after looking for *.txt:
C:/foo.txt
C:/A/foobar.txt
C:/A1/foo.txt
And so on, listing the path to all .txt files on my harddrive. Only the paths, one per line, no extra info needed.
EDIT2:
I've done it. I'm gonna leave this question up for those who make look for this in the future.
The function I used was this(this specific example will hand you a list of all .zip files on your harddrive, edit where needed):
Get-ChildItem -Path c:\ -Include "*.zip" -Recurse -Force -Name > c:\listOfPaths.txt
This created a file called listOfPaths.txt on my C:\ folder and this contained a list of all occurences of any file ending with .zip in all subfolders of my harddrive.
The "c:\" bit isn't mentioned, but I don't mind.
EDIT3:
thanks capar for a more complete version.
Here is capar's code(or how I got it to work, since Get-Children doesn't work in 1.0)
Get-ChildItem -Path c:\ -Recurse *.txt | Select-Object -Property FullName
Since it's Friday night, I decided to play with Power Shell to see if I can help :)
This comes pretty close to what you are asking for I think:
Get-ChildItem -Path c:\ -Recurse *.txt | Select-Object -Property FullName
If it helps, this command will list the properties of any object that will be returned by Get-ChildItem:
Get-ChildItem | Get-Member
ls c:\ -r | ? {$_.name -eq "notepad.exe"}
Get-Children is not recognized in Powershell V3 either. It would be great if someone removed that bad example.
As a warning to anyone searching for files: C:\ on today's hard drives will take a long time to run. You are well advised to narrow your search as much as you can. Since your folder structure might include spaces or special characters, use the typewriter quote (") or apostrophe (') delimeters.
$mylistoffiles = Get-ChildItem -Path 'C:\Windows\Setup\Scripts' -Recurse *.cmd | Select-Object -Property FullName
$mylistoffiles