【问题标题】:Powershell Script to copy file to new folderPowershell脚本将文件复制到新文件夹
【发布时间】:2023-06-04 00:03:01
【问题描述】:

我是 Powershell 脚本的新手,我必须编写一个脚本,从某个路径复制文件并将其粘贴到使用当前日期创建的新文件夹中。这是我目前得到的。

New-Item -Path "c:\users\random\desktop\((Get-Date).ToString('yyyy-MM-dd'))" -ItemType Directory

copy-item c:\users\random\desktop\rand.txt 'c:\users\random\desktop\((Get-Date).ToString('yyyy-MM-dd'))

当我运行这个脚本时,它会创建一个名为((Get-Date).ToString('yyyy-MM-dd')) 的目录,而不是今天的日期。

当此脚本运行时,它必须创建一个包含当前日期的目录并将该文件粘贴到其中。因此,如果我每天运行一次,持续 5 天,它应该创建 5 个不同的文件夹,每个文件夹中都有文件。非常感谢任何帮助。

【问题讨论】:

    标签: powershell scripting


    【解决方案1】:

    如果您希望保留这两行代码,您需要将Get-Date 部分包装在$() 中。这告诉 PS 在使用双引号内的字符串之前解析该代码。

    所以你的代码应该是这样的:

    New-Item -Path "c:\users\random\desktop\$((Get-Date).ToString('yyyy-MM-dd'))" -ItemType Directory
    copy-item c:\users\random\desktop\rand.txt "c:\users\random\desktop\$((Get-Date).ToString('yyyy-MM-dd'))"
    

    但是,如果您的脚本在午夜后的几微秒内执行,您可能会遇到一个缺陷:每个命令都会获得一个单独的日期。

    一个更好的使用方法是简单地获取一个变量中的日期并在你的两个命令中使用它。它还将使其更具可读性:

    $cDate = Get-Date -format yyyy-MM-dd
    $NewPath = "C:\Users\random\desktop\$cDate"
    New-Item -Path $NewPath -ItemType Directory
    Copy-Item c:\users\random\desktop\rand.txt $NewPath
    

    如果您在运行时碰巧经过午夜,这将确保您获得相同的日期值。虽然,这可能不是问题,但安全也无妨。

    【讨论】:

      【解决方案2】:

      括号前少了一个美元符号

      "c:\users\random\desktop**$**((Get-Date).ToString('yyyy-MM-dd'))"

      【讨论】:

      • "c:\users\random\desktop$((Get-Date).ToString('yyyy-MM-dd'))"
      【解决方案3】:

      创建一个变量来存储您的 GetDate,然后将其转换为字符串。

      $currentdate = date $currentdate2 = $currentdate.ToString("yyyy-MM-dd")

      因此您的代码文件夹路径将是 'c:\users\random\desktop\$currentdate2'

      【讨论】:

      • 对了,这不应该是serverfault吗?