我在使用Copy-Item和Veriable作为目的地时遇到问题

问题描述

这可能很容易。但是我可以弄清楚我的简单复制脚本出了什么问题。 我有一个共享目录,可从中复制项目。我正在打印控制台的目标路径,所以我知道它是正确的,但是我收到一个我不明白的Powershell错误

这是我的剧本

#Files to copy
#Get Installers from folder
$APPS = Get-ChildItem \\Server1\shared\APPS -Name 

#ForEach loop to identify and move files
ForEach($APP in $APPS) {
    $dest = "\\Server1\Shared\APPS\$APP"
    #Write-host to see destination path on console
    write-host $dest 
    #copy item from destination path to local directory
    copy-Item $dest -Destination "c:\apps\"
    
 }

这似乎很简单。但是我不明白为什么会收到以下错误

 \\Server1\Shared\APPS\LTCDesktopSetup.exe
copy-Item : The filename,directory name,or volume label Syntax is incorrect.
At C:\Users\computer1\documents\PowerShell\Moving Installer to local drive.ps1:13 char:2
    +     copy-Item $dest -Destination "c:\apps\"
    +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [copy-Item],IOException
    + FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.copyitemcommand

解决方法

奥古斯托,

我建议使用以下语法:

$APPS = (Get-ChildItem "\\mybooklive\CMShared\NAS-Downloads" -filter *.exe).FullName

ForEach ($App in $Apps) {
    copy-item "$APP" -Destination "G:\Test\Copy-Test" -Force
}

或更紧凑:

$APPS = (Get-ChildItem "\\mybooklive\CMShared\NAS-Downloads" -filter *.exe).FullName |
    copy-item -Destination "G:\Test\Copy-Test" -Force

获取FullName与Name,因此您不必重新添加源路径。 使用-Filter,因此您仅获取.exe文件(这是来自变量名$ Apps的假设)。 该部队将解决一些IO问题,例如文件已存在。

HTH 自然,您必须用自己的路径代替我的测试路径。