复制文件,跳过正在使用的文件

我正在尝试使PowerShell脚本每天晚上运行,将C:\ share1中的PDF文件复制到C:\ share2并写入事件日志。

我目前的文件复制脚本位看起来像这样:

Try { get-childitem -Path C:\Share1 | ForEach-Object { Copy-Item $_.FullName C:\share2 -verbose } #Writes to event log as success. } Catch #Logs the event as failed } 

我遇到的问题是复制/replace的文件正在使用中。 当文件正在使用时,脚本将停止在该文件上复制,并出现错误:

 PS>TerminatingError(Copy-Item): "The process cannot access the file 'C:/share2/1.pdf' because it is being used by another process." 

我想至less修改我的脚本,以便继续复制剩余的文件。

如果我例如有100个文件,第三个正在使用,整个传输停止。

我怎样才能修改我的脚本继续其余的项目?

你正在寻找common- -ErrorAction参数设置为-ErrorAction

 get-childitem -Path C:\Share1 | ForEach-Object { Copy-Item $_.FullName C:\share2 -verbose -ErrorAction SilentlyContinue } 

注意:不需要这里的Foreach-Object cmdlet:

 Get-ChildItem -Path C:\Share1 | Copy-Item C:\share2 -verbose -ErrorAction SilentlyContinue 

注2:正如gvee所提到的,这将忽略所有错误。 另一个选择是使用sysinternals套件中的handle.exe来检查是否有打开的句柄。