【问题标题】:Powershell copy-item using variable source names使用变量源名称的 Powershell 复制项
【发布时间】:2020-09-02 19:25:17
【问题描述】:

我是 PowerShell 新手,但仍在尝试解决问题。我有一个脚本可以成功地将文件从一个位置复制到另一个位置:

Copy-Item \\ServerName01\FolderName\file_09022020_0030.txt 
    -Destination \\ServerName02\FolderName\file_copied.txt

如何编写脚本以使用可变源文件名?我想用一个变量找到今天的日期减去7天,并抓取对应的文件。

前:

Copy-Item \ServerName01\FolderName\file_[variable today minus 7]*.txt 
    -Destination \ServerName02\FolderName\file_copied.txt

变量日期应采用 MMDDYYYY 格式。每个文件末尾的时间戳可以忽略,所以我猜这是通配符 (*)

每天都会发布一个新文件,但文件名遵循一个模式:

file_09022020_0030.txt
file_09012020_0030.txt
file_08312020_0305.txt
...
file_08262020_0451.txt
file_08252020_0305.txt
file_08242020_0305.txt

【问题讨论】:

标签: powershell variables copy-item


【解决方案1】:
# Get a string representing 7 days ago in the specified format
# and store it in variable $dt
$dt = (Get-Date).AddDays(-7).ToString('MMddyyyy')

# Use variable $dt in the source file path pattern.
Copy-Item -Path        \\ServerName01\FolderName\file_${dt}_*.txt `
          -Destination \\ServerName02\FolderName\file_copied.txt

注意变量名dt 周围的{...},这是告诉PowerShell 变量名在哪里结束所必需的,因为_ 是变量名中的有效字符。

也就是说,对于中间变量没有严格的要求,因此您可以直接$((Get-Date).AddDays(-7).ToString('MMddyyyy')) 嵌入到源路径中,而不是${dt},通过$(),@ 987654321@.

另见:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    相关资源
    最近更新 更多