none
Remove-Item followed by New-Item puts back same file RRS feed

  • Question

  • My script saves an empty file on a share to denote an event occurred on a server.   If the event occurs again, the file is replaced with a new one with the current creation time.   The problem is after a Remove-Item, then New-Item with the same file name the new file is really the old file with the LastWriteTime updated.   The below code snippet will demonstrate the issue. 

    $path="D:\temp\myfile.txt"
    New-Item -Path $path -ItemType file
    Get-ChildItem -Path | Select name,creationtime,lastwritetime
    Start-Sleep -seconds 5
    Remove-Item $path -force
    Get-ChildItem -Path | Select name,creationtime,lastwritetime
    Start-Sleep -Seconds 5
    New-Item -Path $path -ItemType file
    Get-ChildItem -Path | Select name,creationtime,lastwritetime

    How can I get the file deleted, and a new one to replace the old file?

    Tuesday, February 25, 2014 3:23 PM

Answers

  • Looked it up a little, and there actually is a way to do it. There is a .NET method to change the creation time:

    [System.IO.File]::SetCreationTime("C:\exampleFolder\exampleFile.txt", (Get-Date))

    This will reset the creation date :)

    Cheers,
    Fred


    There's no place like 127.0.0.1


    • Edited by FWN Tuesday, February 25, 2014 4:26 PM
    • Marked as answer by Dave Charles Tuesday, February 25, 2014 5:53 PM
    Tuesday, February 25, 2014 4:26 PM

All replies

  • Not a scripting question, but this feature has been around for a long time.

    The apocryphal history of file system tunnelling

    Windows NT Contains File System Tunneling Capabilities (KB article 172190)

    Bill

    Tuesday, February 25, 2014 3:51 PM
    Moderator
  • Hi Dave,

    while it may not be possible to solve your problem, there may be a workaround:
    Why not have your script put the current Datetime (Get-Date) as the content of the file?

    That should work just as well.

    Cheers,
    Fred


    There's no place like 127.0.0.1

    Tuesday, February 25, 2014 4:16 PM
  • Looked it up a little, and there actually is a way to do it. There is a .NET method to change the creation time:

    [System.IO.File]::SetCreationTime("C:\exampleFolder\exampleFile.txt", (Get-Date))

    This will reset the creation date :)

    Cheers,
    Fred


    There's no place like 127.0.0.1


    • Edited by FWN Tuesday, February 25, 2014 4:26 PM
    • Marked as answer by Dave Charles Tuesday, February 25, 2014 5:53 PM
    Tuesday, February 25, 2014 4:26 PM
  • Thanks!!   That solves my problem, with a slight obvious modification of also resetting the LastWriteTime and LastAccessTime the same way. 

    I appreciate the help.

    Dave


    Wing Rider

    Tuesday, February 25, 2014 5:59 PM