Bat script to retrieve folder size (windows) - windows

I need to write a script .bat that give me the free space of a certain disk and the detail of all folders with the relative dimension and write it in a simple text file (just to check the distribution of used space).
Thanks a lot in advance!

dir /a /s | findstr /b /c:" " > file.txt

The FileSystemObject can do this for you. It is accessible from PowerShell (among other sources).
PowerShell -NoProfile -Command "$fso = New-Object -COMObject Scripting.FileSystemObject; Get-ChildItem YOUR_ROOT_DIRECTORY -Recurse -Directory | %% { $f = $fso.GetFolder($_.FullName); '{0},{1}' -f $f.Size,$_.FullName };"

Related

CMD Dir : i can use * instead subfolder

This is my tree:
f:\mega\user1\rubbish\
f:\mega\user2\rubbish\
f:\mega\user3\rubbish\
.....
f:\mega\usern\rubbish\
I would like (ONLY) list all files inside the various "rubbish" folders.
I tried without success this command:
DIR F:\mega\*\rubbish\
Any suggestions?
Try this from a cmd.exe prompt.
powershell -NoLogo -NoProfile -Command ^
"Get-ChildItem -Directory -Path 'F:\mega\*\rubbish'"
Of course, it is easier in a PowerShell console or .ps1 file script.
Get-ChildItem -Directory -Path 'F:\mega\*\rubbish'
Or, possibly this to limit the names to 'user*' subdirectories.
Get-ChildItem -Directory -Path 'F:\mega\user*\rubbish'
To get only the fully qualified path to the files...
(Get-ChildItem -Directory -Path 'F:\mega\user*\rubbish').FullName
Wildcards can only be used in the last element of a path but not somewhere else.
You could however use a for /D loop to resolve the sub-directories:
for /D %I in ("F:\mega\user*") do #dir "%~I\rubbish"
To use that code in a batch file do not forget to double the %-signs:
for /D %%I in ("F:\mega\user*") do #dir "%%~I\rubbish"

How do I execute a command one after another, each at a separate time?

In Windows Terminal, I am able to execute several commands at the same i.e.:
echo %time% && timeout 3 && echo %time%
However, when executing the above command, It will result in something like:
9:27:57.41
0 秒待っています。続行するには何かキーを押してください ... (My operating system
is Japanese)
9:27:57.41
As you can see, echo %time% is not executed at a different time even though there was a 3 second timeout in between.
How would I separate these two executions?
The End goal here is to measure the the time it takes to perform dir /s C:\.
I tried different things such as:
Powershell -C "Measure-Command {cmd /c dir /s C:\ | Output-Default}" > test.txt
or from Powershell:
Measure-Command{cmd /c dir /s C:\ | Output-Default} > test.txt
But neither of these commands result in the same result I get from running just dir /s C:\ in Terminal. There are differences in time and file count.
I thought I could try:
echo %time% >> test & dir /s C:\ >> test & echo %time% >> test
as an alternative to the Measure-Command but that is not the case...
Something similar can easily be done in linux i.e date +%N && sleep 1 && date +%N or date +%s && sleep 1 && date +%s so why not the almighty Powershell? (a bit of sarcasm)
Any other alternatives I could try or shedding some light to how this all works would help a ton.
EDIT:
With the help from Drew, I was able to do this with the Get-ChildItem method in Powershell. However, this only took a fraction of the time it would take with dir /s. The key goal here is to measure how long it takes with dir so this is mandatory.
EDIT2:
Seems like writing the standard output to the terminal was taking time and not the command itself. Redirecting the output to a File or > NUL was much faster.
Kind regards.
So DIR /S will scan all files in the directory and sub-directory. The PowerShell equivalent of this is -File and -Recurse. So putting these into practice, the entire PowerShell command would be:
Measure-Command -Expression {
Get-ChildItem -Path "C:\" -Recurse -File
} | Out-File C:\test.txt
This will only give you the time taken, not the amount of files. To get the amount of files, you will need to change it up a little.
Measure-Command -Expression {
(Get-ChildItem -Path "C:\" -Recurse -File).Count | Out-File C:\FileCount.txt
} | Out-File C:\test.txt
Alternatively, you could run this and get something a little nicer. and each task is split up on a new line.
$Path = "C:\"
$StartTime = Get-Date
$FileCount = (Get-ChildItem -Path $Path -Recurse -File).Count
$EndTime = Get-Date
$TimeTaken = New-TimeSpan –Start $StartTime –End $EndTime
"Found $FileCount files in $Path which took $($TimeTaken.Seconds) Seconds" | Out-File C:\test.txt

Change the content of multiple text files

I would like to find every instance of "blue" and change it to "pink" in multiple text files. I cannot download FAR (Find And Replace) softwares so I need to use what is already on the computer: Powershell/cmd/batch.
Not knowing how to do this for multiple files in Powershell, I decided to combine batch and Powershell. This is the batch code I currently have:
for %%F in ("C:\mypath\*") do (
powershell -command(get-content %%F) -replace 'blue', 'pink'| set-content -encoding ASCII %%F
)
This does not work, I receive the error message "set-content is not recognized as an internal command".
I realize that using two languages together can lead to some issues, so is this doable exclusively with batch or exclusively with Powershell?
Thank you.
This is the completed code. It finds "blue" and replaces it with "pink" through multiple files, with a path that includes spaces:
for %%F in ("C:\mypath\*") do powershell -command "(get-content '%%F') -replace 'blue', 'pink'| set-content -encoding ASCII '%%F'"
Thanks to Aacini, Squashman and Compo for their help.
You should using only PowerShell if you can :
Get-ChildItem "C:\mypath" -file | %{$path=$_.FullName; (Get-Content $path).Replace('blue', 'pink') | set-content $path -encoding ASCII }

Startup script to generate uninstall command

I have a text file of the format:
computername1 uninstallkey1
computername2 uninstallkey2
...
computername200 uninstallkey200
I am trying to write a startup script (batch file or powershell?) that generates a msiexec command that looks up and implants the correct key for each computer it executes on e.g.:
msiexec /x install.msi key=uninstallkey
If I have not made anything clear, please ask and any help is much appreciated!
#ECHO OFF
SETLOCAL
FOR /f "tokens=1*" %%i IN (yourtextfilename.txt) DO (
IF /i %%i==%COMPUTERNAME% ECHO MSIEXEC /x install.msi key=%%j
)
This should do as you require - yourtextfilename.txt contains the data, presumably on a shared drive; finds the line where the computername in column 1 is the same as the computername returned by %computername% in the target computer's environment.
(all case-insensitive EXCEPT %%i and %%j which must match and be the same case)
Command simply ECHOed - remove the ECHO keyword after verification to activate.
In PowerShell,
$comp = Import-CSV -Delimiter " " -Path C:\comp.txt -Header computername,uninstallkey
$comp | ForEach-Object {
if ($env:COMPUTERNAME -eq $_.Computername) {
Start-Process -FilePath "msiexec.exe" -ArgumentList "/x install.msi key=$_.uninstallkey"
}
}

how to empty recyclebin through command prompt?

Usually we delete the recycle bin contents by right-clicking it with the mouse and selecting "Empty Recycle Bin". But I have a requirement where I need to delete the recycle bin contents using the command prompt. Is this possible? If so, how can I achieve it?
You can effectively "empty" the Recycle Bin from the command line by permanently deleting the Recycle Bin directory on the drive that contains the system files. (In most cases, this will be the C: drive, but you shouldn't hardcode that value because it won't always be true. Instead, use the %systemdrive% environment variable.)
The reason that this tactic works is because each drive has a hidden, protected folder with the name $Recycle.bin, which is where the Recycle Bin actually stores the deleted files and folders. When this directory is deleted, Windows automatically creates a new directory.
So, to remove the directory, use the rd command (r​emove d​irectory) with the /s parameter, which indicates that all of the files and directories within the specified directory should be removed as well:
rd /s %systemdrive%\$Recycle.bin
Do note that this action will permanently delete all files and folders currently in the Recycle Bin from all user accounts. Additionally, you will (obviously) have to run the command from an elevated command prompt in order to have sufficient privileges to perform this action.
I prefer recycle.exe from Frank P. Westlake. It provides a nice before and after status. (I've been using Frank's various utilities for well over ten years..)
C:\> recycle.exe /E /F
Recycle Bin: ALL
Recycle Bin C: 44 items, 42,613,970 bytes.
Recycle Bin D: 0 items, 0 bytes.
Total: 44 items, 42,613,970 bytes.
Emptying Recycle Bin: ALL
Recycle Bin C: 0 items, 0 bytes.
Recycle Bin D: 0 items, 0 bytes.
Total: 0 items, 0 bytes.
It also has many more uses and options (output listed is from /?).
Recycle all files and folders in C:\TEMP:
RECYCLE C:\TEMP\*
List all DOC files which were recycled from any directory on the C: drive:
RECYCLE /L C:\*.DOC
Restore all DOC files which were recycled from any directory on the C: drive:
RECYCLE /U C:\*.DOC
Restore C:\temp\junk.txt to C:\docs\resume.txt:
RECYCLE /U "C:\temp\junk.txt" "C:\docs\resume.txt"
Rename in place C:\etc\config.cfg to C:\archive\config.2007.cfg:
RECYCLE /R "C:\etc\config.cfg" "C:\archive\config.2007.cfg"
nircmd lets you do that by typing
nircmd.exe emptybin
http://www.nirsoft.net/utils/nircmd-x64.zip
http://www.nirsoft.net/utils/nircmd.html
You can use a powershell script (this works for users with folder redirection as well to not have their recycle bins take up server storage space)
$Shell = New-Object -ComObject Shell.Application
$RecBin = $Shell.Namespace(0xA)
$RecBin.Items() | %{Remove-Item $_.Path -Recurse -Confirm:$false}
The above script is taken from here.
If you have windows 10 and powershell 5 there is the Clear-RecycleBin commandlet.
To use Clear-RecycleBin inside PowerShell without confirmation, you can use Clear-RecycleBin -Force. Official documentation can be found here
I use this powershell oneliner:
gci C:\`$recycle.bin -force | remove-item -recurse -force
Works for different drives than C:, too
You can use this PowerShell command.
Clear-RecycleBin -Force
Note: If you want a confirmation prompt, remove the -Force flag
To stealthily remove everything, try :
rd /s /q %systemdrive%\$Recycle.bin
I know I'm a little late to the party, but I thought I might contribute my subjectively more graceful solution.
I was looking for a script that would empty the Recycle Bin with an API call, rather than crudely deleting all files and folders from the filesystem. Having failed in my attempts to RecycleBinObject.InvokeVerb("Empty Recycle &Bin") (which apparently only works in XP or older), I stumbled upon discussions of using a function embedded in shell32.dll called SHEmptyRecycleBin() from a compiled language. I thought, hey, I can do that in PowerShell and wrap it in a batch script hybrid.
Save this with a .bat extension and run it to empty your Recycle Bin. Run it with a /y switch to skip the confirmation.
<# : batch portion (begins PowerShell multi-line comment block)
:: empty.bat -- http://stackoverflow.com/a/41195176/1683264
#echo off & setlocal
if /i "%~1"=="/y" goto empty
choice /n /m "Are you sure you want to empty the Recycle Bin? [y/n] "
if not errorlevel 2 goto empty
goto :EOF
:empty
powershell -noprofile "iex (${%~f0} | out-string)" && (
echo Recycle Bin successfully emptied.
)
goto :EOF
: end batch / begin PowerShell chimera #>
Add-Type shell32 #'
[DllImport("shell32.dll")]
public static extern int SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath,
int dwFlags);
'# -Namespace System
$SHERB_NOCONFIRMATION = 0x1
$SHERB_NOPROGRESSUI = 0x2
$SHERB_NOSOUND = 0x4
$dwFlags = $SHERB_NOCONFIRMATION
$res = [shell32]::SHEmptyRecycleBin([IntPtr]::Zero, $null, $dwFlags)
if ($res) { "Error 0x{0:x8}: {1}" -f $res,`
(New-Object ComponentModel.Win32Exception($res)).Message }
exit $res
Here's a more complex version which first invokes SHQueryRecycleBin() to determine whether the bin is already empty prior to invoking SHEmptyRecycleBin(). For this one, I got rid of the choice confirmation and /y switch.
<# : batch portion (begins PowerShell multi-line comment block)
:: empty.bat -- http://stackoverflow.com/a/41195176/1683264
#echo off & setlocal
powershell -noprofile "iex (${%~f0} | out-string)"
goto :EOF
: end batch / begin PowerShell chimera #>
Add-Type #'
using System;
using System.Runtime.InteropServices;
namespace shell32 {
public struct SHQUERYRBINFO {
public Int32 cbSize; public UInt64 i64Size; public UInt64 i64NumItems;
};
public static class dll {
[DllImport("shell32.dll")]
public static extern int SHQueryRecycleBin(string pszRootPath,
out SHQUERYRBINFO pSHQueryRBInfo);
[DllImport("shell32.dll")]
public static extern int SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath,
int dwFlags);
}
}
'#
$rb = new-object shell32.SHQUERYRBINFO
# for Win 10 / PowerShell v5
try { $rb.cbSize = [Runtime.InteropServices.Marshal]::SizeOf($rb) }
# for Win 7 / PowerShell v2
catch { $rb.cbSize = [Runtime.InteropServices.Marshal]::SizeOf($rb.GetType()) }
[void][shell32.dll]::SHQueryRecycleBin($null, [ref]$rb)
"Current size of Recycle Bin: {0:N0} bytes" -f $rb.i64Size
"Recycle Bin contains {0:N0} item{1}." -f $rb.i64NumItems, ("s" * ($rb.i64NumItems -ne 1))
if (-not $rb.i64NumItems) { exit 0 }
$dwFlags = #{
"SHERB_NOCONFIRMATION" = 0x1
"SHERB_NOPROGRESSUI" = 0x2
"SHERB_NOSOUND" = 0x4
}
$flags = $dwFlags.SHERB_NOCONFIRMATION
$res = [shell32.dll]::SHEmptyRecycleBin([IntPtr]::Zero, $null, $flags)
if ($res) {
write-host -f yellow ("Error 0x{0:x8}: {1}" -f $res,`
(New-Object ComponentModel.Win32Exception($res)).Message)
} else {
write-host "Recycle Bin successfully emptied." -f green
}
exit $res
while
rd /s /q %systemdrive%\$RECYCLE.BIN
will delete the $RECYCLE.BIN folder from the system drive, which is usually c:,
one should consider deleting it from any other available partitions since there's an hidden $RECYCLE.BIN folder in any partition in local and external drives (but not in removable drives, like USB flash drive, which don't have a $RECYCLE.BIN folder).
For example, I installed a program in d:, in order to delete the files it moved to the Recycle Bin I should run:
rd /s /q d:\$RECYCLE.BIN
More information available at Super User at Empty recycling bin from command line
i use these commands in a batch file to empty recycle bin:
del /q /s %systemdrive%\$Recycle.bin\*
for /d %%x in (%systemdrive%\$Recycle.bin\*) do #rd /s /q "%%x"
Yes, you can Make a Batch file with the following code:
cd \Desktop
echo $Shell = New-Object -ComObject Shell.Application >>FILENAME.ps1
echo $RecBin = $Shell.Namespace(0xA) >>FILENAME.ps1
echo $RecBin.Items() ^| %%{Remove-Item $_.Path -Recurse -Confirm:$false} >>FILENAME.ps1
REM The actual lines being writen are right, exept for the last one, the actual thigs being writen are "$RecBin.Items() | %{Remove-Item $_.Path -Recurse -Confirm:$false}"
But since | and % screw things up, i had to make some changes.
Powershell.exe -executionpolicy remotesigned -File C:\Desktop\FILENAME.ps1
This basically creates a powershell script that empties the trash in the \Desktop directory, then runs it.
Create cmd file with line:
for %%p in (C D E F G H I J K L M N O P Q R S T U V W X Y Z) do if exist "%%p:\$Recycle.Bin" rundll32.exe advpack.dll,DelNodeRunDLL32 "%%p:\$Recycle.Bin"
I use EmptyRecycleBin.py python script
You will need to pip install winshell
#!python3
# Empty Windows Recycle Bin
import winshell
try:
winshell.recycle_bin().empty(confirm=False, show_progress=True, sound=False)
print("Recycle Bin emptied")
except:
print('Recycle Bin is already empty')
You can change the Boolean False and True statements to either turn on or off the following:
Confirm yes\no dialog, progress bar, sound effect.
If you don't use python, this one-liner for powershell is great.
I actually have it in EmptyRecycleBin.ps1, and use it in Git Bash.
Clear-RecycleBin -Force
All of the answers are way too complicated. OP requested a way to do this from CMD.
Here you go (from cmd file):
powershell.exe /c "$(New-Object -ComObject Shell.Application).NameSpace(0xA).Items() | %%{Remove-Item $_.Path -Recurse -Confirm:$false"
And yes, it will update in explorer.

Resources