Yots
Yots

Reputation: 1685

Setting multiple properties at once in Powershell

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.

Upvotes: 6

Views: 2381

Answers (2)

mjolinor
mjolinor

Reputation: 68243

"CreationTime","LastWriteTime","LastAccessTime" |% {(gi test.txt).$_ = (get-date)}

Upvotes: 8

AeroX
AeroX

Reputation: 3443

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
    }
}

Upvotes: 0

Related Questions