【问题标题】:Setting multiple properties at once in Powershell在 Powershell 中一次设置多个属性
【发布时间】:2011-05-25 21:48:07
【问题描述】:

有没有比这更短的方法在 Powershell 中通过一个命令将多个属性设置为相同的值?

例子:

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

我只是好奇是否有办法缩短这种语法。

【问题讨论】:

    标签: syntax powershell


    【解决方案1】:
    "CreationTime","LastWriteTime","LastAccessTime" |% {(gi test.txt).$_ = (get-date)}
    

    【讨论】:

    • 只是为了好玩,你也可以这样做:$test.CreationTime, $test.LastWriteTime, $test.LastAccessTime = @(get-date) * 3
    • 您的两个答案在语义上与操作的示例并不完全相同。保证所有三个道具的 OP 日期相同。在你的情况下,不是这样。 foreach-object 和 * 乘数都有可能发生翻转。
    【解决方案2】:

    我使用了 Mjolinor 答案的略微修改版本来解决我刚刚从远程源下载的文件的日期不正确的问题。我修改了代码,使其更易于理解,以防我将来必须返回(将简写更改为完整的命令名称)。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-03
      • 2020-01-24
      • 2012-03-08
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 2012-06-03
      • 2018-12-08
      相关资源
      最近更新 更多