How to finish this batch script after set /p not allowing

SK_-_ 21 Reputation points
2021-02-17T18:29:01.87+00:00

Hi,

I found this post which does exactly what I need but the 2nd part doesn't work and when I try run it plan in cmd I get the following error "The process cannot access the file because it is being used by another process."

In short, I'm trying to run a script which is being run by a schedule for every time I log in or out of the pc it should record the time and date to a csv, so I have 2 scripts
1 when I login which goes like this "set /p = %DATE%, %TIME% >> D:\Users\USER2\desktop\log-1.csv"
2 when I logout it goes like this "echo %TIME% >> D:\Users\USER2\desktop\log-1.csv" but the 2nd one doesn't run

Thanks for any help!

Windows for business | Windows Server | User experience | PowerShell
Windows for business | Windows Client for IT Pros | User experience | Other
0 comments No comments
{count} votes

Accepted answer
  1. MotoX80 36,291 Reputation points
    2021-02-17T20:55:00.417+00:00

    Assuming that you are using a .bat file and not Powershell, you missed the "< nul" part.

    That post also commented about what the log looks like if the PC crashes and a logoff event is not written. You will have the same issue. To work around that, you will have use that trick on both logon and logoff scripts.

    In the logon script, write a new line first.

    @echo.>> D:\Users\USER2\desktop\log-1.csv
    set /p =%computername%,%username%,%TIME:~0,5%,%date%,< nul >> D:\Users\USER2\desktop\log-1.csv
    

    The logoff script.

    set /p =%TIME:~0,5%,%date%< nul >>D:\Users\USER2\desktop\log-1.csv
    

1 additional answer

Sort by: Most helpful
  1. Rich Matheisen 47,901 Reputation points
    2021-02-17T20:15:21.38+00:00

    PowerShell doesn't use "set" to create environment variables. "Set" is a PowerShell alias for the "Set-Variable" cmdlet. Nor does PowerShell reference environment variables in the same way that the cmd.exe shell does (by surrounding them with "%" characters. In your example, to get the time and date you'll use Get-Date.

    If you say "set /p = "AAA"" you'll get an error: Set-Variable : A positional parameter cannot be found that accepts argument 'AAA'. If you say "Set /p AAA" (without the "=") you'll create a variable named "/p" with a value of "AAA". However, because there's a "/" in the name you'll find it hard to use that variable in the normal way -- you'll have to use "Get-Variable /p -ValueOnly"

    PowerShell references environment variables by prefixing the name with "Env:". See about_Environment_Variables. about_environment_variables

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.