6

Is there a shorter way to set multiple properties to the same value in Powershell in one command than this?

Example:

(gi  "c:\test.txt").LastWriteTime = (gi  "c:\test.txt").LastAccessTime = (gi  "c:\test.txt").CreationTime = Get-date

I'm just curious if there is a way to shorten this syntax.

2 Answers 2

8
"CreationTime","LastWriteTime","LastAccessTime" |% {(gi test.txt).$_ = (get-date)}
Sign up to request clarification or add additional context in comments.

2 Comments

Just for fun, you can also do this: $test.CreationTime, $test.LastWriteTime, $test.LastAccessTime = @(get-date) * 3
Both your answers are not quite the same, semantically, as the op's example. The OP is guaranteed the same date on all three props. In your cases, not so. There's a chance of a roll over in both the foreach-object and the * multiplier.
0

I've used a slightly modified version of Mjolinor's answer to solve a problem I had of incorrect date on files that had just been downloaded from a remote source. I modified the code to make it cleaner to understand in case I have to come back to in the future (changed the short hand to full command names).

# Correct Access/Create/Write times on transferred files
ForEach( $File in $TransferList ) {
    @("CreationTime","LastAccessTime","LastWriteTime") | ForEach {
        $(Get-Item $File.Name).$_ = $File.Date
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.