Search code examples
windowspowershellcmdterminalcommand-prompt

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.


Solution

  • 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