1

I have the script below, I am trying to use copy-item to copy two files. Unfortunately the file path include spaces in them, and I need to use variables to capture the correct files. I have used Test-Path to try and qualify the path, which seem to work, but in the script it is all failures.

$Today = Get-Date -Format "yyyyMMdd"
$Yesterday = (Get-Date).AddDays(-1).ToString('yyyyMMdd')

$folderdate = $Yesterday
$filedate = (Get-Date).AddDays(-1).ToString('dd.MM.yy')

Copy-Item -Path \\posa1251\d$\File_Transfer\NBS\$Today\Daily MI $Yesterday'.xlsx' -Destination \\wbbsmd.co.uk\corpdata\Corp\Group\NBS_WebSave_Reports\$folderdate\
Copy-Item -Path \\posa1251\d$\File_Transfer\NBS\$Yesterday\$filedate' - West Brom MI.xls' -Destination \\wbbsmd.co.uk\corpdata\Corp\Group\NBS_WebSave_Reports\$folderdate\

The file paths without the variables are below:

\\posa1251\d$\File_Transfer\NBS\20230201\Daily MI 20230131.xlsx
\\posa1251\d$\File_Transfer\NBS\20230131\31.01.23 - West Brom MI.xls
\\wbbsmd.co.uk\corpdata\Corp\Group\NBS_WebSave_Reports\20230131\

Any suggestions would be gratefully received.

Daniel Mann
  • 57,011
  • 13
  • 100
  • 120

1 Answers1

1

Essentially, your paths should be wrapped in a expandable string "..." otherwise each value between the spaces are interpreted and bound to other parameters, considering there are available positional parameters available. See about Parameters for more details.

Take the following simple function to understand what's happening:

function Test {
    param(
        [Parameter(Mandatory)]
        [string[]] $Path,

        [Parameter(Mandatory)]
        [string] $Destination,

        [Parameter(ValueFromRemainingArguments)]
        [object[]] $RemainingArgs
    )

    $PSBoundParameters
}

If we try the paths without quotes:

Test -Path \\posa1251\d$\File_Transfer\NBS\$Today\Daily MI $Yesterday'.xlsx' -Destination \\wbbsmd.co.uk\corpdata\Corp\Group\NBS_WebSave_Reports\$folderdate\

We can see that MI and 20230201.xlsx are being bound to other, remaining in this case, parameters:

Key           Value
---           -----
Path          {\\posa1251\d$\File_Transfer\NBS\20230202\Daily}
Destination   \\wbbsmd.co.uk\corpdata\Corp\Group\NBS_WebSave_Reports\\
RemainingArgs {MI, 20230201.xlsx}

Instead, if we use quotes:

Test -Path "\\posa1251\d$\File_Transfer\NBS\$Today\Daily MI $Yesterday.xlsx" -Destination "\\wbbsmd.co.uk\corpdata\Corp\Group\NBS_WebSave_Reports\$folderdate\"

There shouldn't be any problem:

Key         Value
---         -----
Path        {\\posa1251\d$\File_Transfer\NBS\20230202\Daily MI 20230201.xlsx}
Destination \\wbbsmd.co.uk\corpdata\Corp\Group\NBS_WebSave_Reports\\
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37