0

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
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Matthew
  • 111
  • 7
  • 3
    Check out help about [variables](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_variables?view=powershell-7) and use [Get-Date](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-date?view=powershell-7) to pick a date. – vonPryz Sep 02 '20 at 19:52

1 Answers1

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

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:

mklement0
  • 382,024
  • 64
  • 607
  • 775