I'm new to PowerShell and still trying to figure things out. I have a script that will successfully copy a file from one location to another:
Copy-Item \\ServerName01\FolderName\file_09022020_0030.txt
-Destination \\ServerName02\FolderName\file_copied.txt
How can I write the script to use a variable source file name? I want to use a variable to find today's date minus 7 days and grab the corresponding file.
EX:
Copy-Item \ServerName01\FolderName\file_[variable today minus 7]*.txt
-Destination \ServerName02\FolderName\file_copied.txt
The variable date should be in the MMDDYYYY format. The timestamp at the end of each file can be ignored so I'm guessing that's a wildcard (*)
A new file is posted each day but the file name follows a pattern:
file_09022020_0030.txt
file_09012020_0030.txt
file_08312020_0305.txt
...
file_08262020_0451.txt
file_08252020_0305.txt
file_08242020_0305.txt
# 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
Note the {...}
around the variable name, dt
, which is required to tell PowerShell where the variable name ends, given that _
is a valid character in a variable name.
That said, there's no strict need for an intermediate variable, so instead of ${dt}
you could directly embed
$((Get-Date).AddDays(-7).ToString('MMddyyyy'))
in the source path, via $()
, the subexpression operator .
See also:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.