How to empty recycling bin in batch - powershell

I need a code to empty the recycling bin without conformation I have tried the simple del $Recycle.Bin but it says access denied even when elevated does any one know a code I could use.

This emptied my bin without any confirmation.
#ECHO OFF
start /b /wait powershell.exe -command "$Shell = New-Object -ComObject Shell.Application;$RecycleBin = $Shell.Namespace(0xA);$RecycleBin.Items() | foreach{Remove-Item $_.Path -Recurse -Confirm:$false}"

Above answers are ok for cmd batch files but for the new powershell there is a better way
Simply use the cmdlet
Clear-RecycleBin
Optionally you can use the -Force or -Confirm:$false parameters so it won't ask for confirmation
For more info open powershell and type
Get-Help Clear-RecycleBin

I have just found this.
erase /s/q/f "C:\$RECYCLE.BIN\*">nul

Guaranteed to delete all content in the Recycle Bin for the selected drive while leaving the folder itself intact:
C:\$Recycle Bin\>rd . /q /s
Change to the required drive
Change into the $Recycle Bin folder
Run the command rd . /q /s [remove-dir (currentdir) /quiet /subdir]
You will get an error that the current directory is still in use (because that is your current location) and can't be deleted. This is expected behaviour because I want the $Recycle Bin folder to remain.

Related

Delete Windows Update Residuals using Disk Cleanup via Powershell

How can I delete/cleanup all the folders under "Clean System Files" option in disk cleanup via powershell? The code below wasn't able to achieve what I wanted to.
(Start-Process -FilePath "$env:systemroot\system32\cleanmgr.exe" -ArgumentList "/sagerun:1" -Wait -PassThru)
Thank you,
Have you tried the autoclean option?
cleanmgr.exe /AUTOCLEAN
It will clean below folders:
C:$Windows.~BT*
C:$Windows.~LS*
C:$Windows.~WS*
C:\ESD\Download*
C:\ESD\Windows*
C:$WINDOWS.~Q*
C:$INPLACE.~TR*
C:\Windows.old*
C:\Windows\Panther
It will also write 2 log files as following:
C:\Windows\System32\LogFiles\setupcln\setupact.log
C:\Windows\System32\LogFiles\setupcln\setuperr.log
you can delete them one by one by starting the cmd in admin mode.
below is an example to delete the $windows.~BT folder
takeown /F C:\$Windows.~BT\* /R /A
icacls C:\$Windows.~BT\*.* /T /grant administrators:F
rmdir /S /Q C:\$Windows.~BT\

Running PS1 file from batch file, same folder on thumb drive

Admittedly I'm no scripter. I piece together what already works but trying to learn.
I have a script that does a lot of the manual labor for setting up a scan user for myself and our techs. Here is a small portion of it written as a batch file. At the end before the pause I want to call a PowerShell to show what the Network type is, not to change it. At least not at this time. I did remove alot of the extra from the file to save space. Both the batch file and the PS1 file will be in the same folder on a thumb drive.
The nettype.ps1 file just has:
get-netconnectionprofile
pause
The pause of course is so the tech can see the network type.
Hope someone has a simple solution. I did look here and other websites. I may not be using the right terminology in my search or understanding what I need done.
net user Scans Scanner1 /add
net localgroup administrators Scans /add
wmic UserAccount where Name='Scans' set PasswordExpires=False
md C:\Scans
#echo off
NET SHARE Scans=C:\Scans /Grant:Scans,Full
ICACLS "C:\Scans" /Grant Scans:(OI)(CI)(F) /t /c
ICACLS "C:\Scans" /Grant Everyone:(OI)(CI)(F) /t /c
netsh advfirewall firewall set rule group="Network Discovery" new enable=Yes
netsh advfirewall firewall set rule group="File and Printer Sharing" new enable=Yes
PowerShell.exe -File "nettype.ps1"
pause
If that is all you have inside your powershell script, don't run it as a script, delete it and just run the command directly in your batch-file:
"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -Command "Get-NetConnectionProfile"
Which could be probably be shortened to:
PowerShell Get-NetConnectionProfile
I found the answer, knew it would be simple.
Just had to use the following in the batch file:
powershell.exe -ExecutionPolicy Bypass -File ""%~dp0nettype.ps1""
You can change the powershell call to the following to find the ps1 file in the same directory:
powershell.exe -File "%~dp0nettype.ps1"
%~dp0 is a combination of %0 variable and ~d and ~p modifiers.
%0 is the full path to the current batch file.
~d when combined with %0 (e.g. %~d0) will get you drive letter portion (e.g. C:) from %0.
~p when combined with %0 (e.g. %~p0) will get you the path portion of %0 without the filename.
Combining them together, %~dp0, will get you the full path of the folder where current batch file is located.
You can find a complete list of these modifiers here: https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-xp/bb490909(v=technet.10)?redirectedfrom=MSDN
One thing to note, is that %~dp0 modifier only works in batch files, not when you try to run on commandline directly.

Network shared batch file wont change registry

I have following batch file:
powershell -Command "& {Set-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsStore\WindowsUpdate -Name AutoDownload -Value 2 -Type DWord}"
If I run it locally it does make necessary changes to the registry, however if I upload it on a shared folder and execute this batch file via a shared folder it won't change the registry.
What am I missing here exactly? It works fine if file is located on my local computer, but if I will launch it from a shared folder (without downloading locally) no changes are made.
The batch file is called via HTA file with the following code:
function Win10UninstallUnnecessaryApps(){
var shell = new ActiveXObject("WScript.Shell");
var path = '"file:\\\\fs\\FIle Share\\SA Support\\ZverTools\\Win10UninstallUnnecessaryApps.bat"';
shell.run(path,1,false);
}
As you are running the batch file from a network share, so it means that you are not in your local computer. You also need admin privileges. So you have to use this:
#echo off
NET SESSION >NUL 2>&1
IF %ERRORLEVEL% NEQ 0 GOTO elevate
GOTO admintasks
:elevate
pushd %~dp0
MSHTA.exe "javascript: var shell = new ActiveXObject('shell.application'); shell.ShellExecute('%~nx0', '', '', 'runas', 1);close();"
:admintasks
powershell -command invoke-command -computername TheLocalComputerName -scriptblock "& {Set-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsStore\WindowsUpdate -Name AutoDownload -Value 2 -Type DWord}"
Replace TheLocalComputerName with the computer you want to execute this in.
I know the following method is not perfect, but it was the only solution that worked for my case. This is some sort of hack method to perform registry changes executed by the HTA application. You should create a batch file that downloads your another batch file (which has registry changing code inside), after that select that specific file and use the SendKeys method to mimic click event. As soon as I updated my HTA application with the following hack, it worked well and I got my single click registry changes after all.
Here is starting batch file (executed from HTA application button) code which runs another batch file (the one which should edit registry values):
#if (#CodeSection == #Batch) #then
#echo off
set SendKeys=CScript //nologo //E:JScript "%~F0"
xcopy "\\fs\FIle Share\SA Support\ZverTools\Win10UninstallUnnecessaryApps.bat" "%USERPROFILE%" /y
TIMEOUT /T 2 /NOBREAK
set targetfilepath=%USERPROFILE%\Win10UninstallUnnecessaryApps.bat
explorer.exe /select, "%TARGETFILEPATH%"
TIMEOUT /T 4 /NOBREAK
%SendKeys% "{ENTER}"
goto :EOF
#end
var WshShell = WScript.CreateObject("WScript.Shell");
WshShell.SendKeys(WScript.Arguments(0));
This was the only solution that allowed me to change registry values with a single HTA application button click.
Registry value which I wanted to change via batch file (executed from HTA app) was:
powershell -Command "& {Set-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsStore\WindowsUpdate -Name AutoDownload -Value 2 -Type DWord}"

Powershell to unblock all the files in a folder

Trying to make a .bat I can drop in a folder, when run it will unblock all the files in that folder...
#ECHO OFF
PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "& {get-childitem '%~dp0' | unblock-file}"
EXIT
...keeps telling me "The term 'unblock-file' is not recognized as the name of a cmdlet..." no matter how I try to format it, where am I going wrong?
I'm trying to do this so I can just copy the .bat to the folder (and NOT have to copy a .bat and .ps1) so I thought a 1-line powershell "call" was the way to go?
The unblock-file command is available from Powershell 3.0.
Upgrade your PowerShell and script should work
Tested and working:
dir -r | unblock-file
Unblocks everything from the current directory recursively

Number of files deleted from batch file

REM Detect how many files are on the C: drive
dir /s /b C:\ |find /c "\" > NUMfiles.###
set /p count1=<NUMfiles.###
##### TEMP FILES DELETED HERE, RUN CCLEANER, RUN MBAM, ETC #####
REM Calculate Total Files Deleted
dir /s /b C:\ |find /c "\" > NUMfiles.###
set /p count2=<NUMfiles.###
set /a count3=%count1% - %count2%
echo Number of files removed: %count3%
This doesn't seem to be giving me an accurate reading. Can anyone help?
I do a manual check via command line using the 'dir /s /b C:\ |find /c "\"' before the script, and at the end. And the output from '%count3% isn't accurate from my subtraction from the manual checks. Hope you understand my question.
Yes, as snemarch montined, the fact that you list everything and temporary files could as well be added/deleted by another process meanwhile invalidate the entire effort.
On a side note, adding "/a-d" to the "dir" command would remove the directories from being listed, thus not needing VonC's "find /v "" addition to the process, if you insist on checking files only.
Could you not check file while they get deleted instead? Not sure what you use this for but you definately need to rethink the way from source, the deleting part.
My suggestion.
If you must iterate on the all content, this command line might be more precise to list the number of files (files, not directories):
dir /a /s /OG C:\ |find /v "<DIR>" | find /c "M "
Off course, this assume a dir does display 'AM ' or 'PM '.
If it does not, the following should works better:
dir /a /s /OG C:\ |find /v "<DIR>" | find /c "/"