如何在PowerShell脚本中记录Copy-Item命令的执行结果
实现方案
你可以通过-PassThru参数获取Copy-Item的执行结果,搭配-ErrorVariable捕获执行过程中产生的错误,同时可以将结果输出到日志文件做持久化存储,修改后的完整脚本如下:
# 定义路径变量和日志路径 $sourceFolder = 'C:\Windows\CMSLOGS' $targetFolder = 'C:\ProgramData\Microsoft\IntuneManagementExtension\Logs\CMSLOGS' $logPath = 'C:\Windows\Temp\Copy_CMSLogs_Result.log' # 初始化日志 "=== 脚本执行时间: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss') ===" | Out-File -FilePath $logPath -Append # 检测目标文件夹是否存在 "Test to see if folder [$targetFolder] exists" | Tee-Object -FilePath $logPath -Append if (Test-Path -Path $targetFolder) { "Path exists!" | Tee-Object -FilePath $logPath -Append } else { "Path doesn't exist, start creating folder." | Tee-Object -FilePath $logPath -Append New-Item -Path $targetFolder -ItemType Directory -Force | Out-Null } # 复制.log文件并记录结果 "=== 开始复制.log文件 ===" | Tee-Object -FilePath $logPath -Append $copyLogResult = Copy-Item -Path "$sourceFolder\*.log" -Destination $targetFolder -PassThru -ErrorAction SilentlyContinue -ErrorVariable copyLogError if ($copyLogResult) { "成功复制的.log文件列表:" | Tee-Object -FilePath $logPath -Append $copyLogResult.FullName | Tee-Object -FilePath $logPath -Append } if ($copyLogError) { ".log文件复制错误信息:" | Tee-Object -FilePath $logPath -Append $copyLogError | Out-File -FilePath $logPath -Append } # 复制.flg文件并记录结果 "=== 开始复制.flg文件 ===" | Tee-Object -FilePath $logPath -Append $copyFlgResult = Copy-Item -Path "$sourceFolder\*.flg" -Destination $targetFolder -PassThru -ErrorAction SilentlyContinue -ErrorVariable copyFlgError if ($copyFlgResult) { "成功复制的.flg文件列表:" | Tee-Object -FilePath $logPath -Append $copyFlgResult.FullName | Tee-Object -FilePath $logPath -Append } if ($copyFlgError) { ".flg文件复制错误信息:" | Tee-Object -FilePath $logPath -Append $copyFlgError | Out-File -FilePath $logPath -Append } "=== 脚本执行完成 ===" | Tee-Object -FilePath $logPath -Append
改动说明
Copy-Item增加了-PassThru参数,执行成功后会返回复制的文件对象,你可以直接读取该对象的属性确认复制的文件路径、大小等信息- 增加
-ErrorVariable参数捕获执行错误,搭配-ErrorAction SilentlyContinue可以避免脚本因为复制错误直接中断执行,同时错误信息会存入指定的变量中供后续日志记录 - 使用
Tee-Object命令可以让输出内容同时显示在控制台和写入日志文件,方便调试和后续排查,你可以根据自己的需求修改日志存储路径$logPath - 原来的
Mkdir替换为PowerShell原生的New-Item命令,增加-Force参数避免创建文件夹时出现权限提示或者重复创建报错
内容的提问来源于stack exchange,提问作者user9099
相关产品推荐
相关产品推荐

