小编Bag*_*ger的帖子

$ Files中的PowerShell ForEach $文件

我有一个PowerShell脚本,可以获取文件列表并移动符合特定条件的文件.为什么foreach即使对象为空,循环也会运行?

我会假设如果$ i不存在它就不会运行.但是如果$ filePath中没有结果,为什么forEach循环运行一次呢?我已经解决了我的问题,但我很好奇,我尝试搜索,但我找不到答案.

为了使这个工作,我只是检查以确保在forEach循环之前存在$ filePath.

例如,if($ filePath){...

 $filePath = Get-ChildItem -Path $sourceDir | Where-Object {! $_.PSIsContainer -AND ($_.Name -Match "^XXX_XXX*" -OR $_.Name -Match "^YYY_XX*")}

 ForEach($i in $filePath){
     $sfName =  $i.Name
     $sfDir = $i.Directory
     $tFileName = testFile $destDir $sfName
     $sFile = $sourceDir + $sfName
     $tFile = $destDir + $tFileName

     moveFile $sFile $tFile
Run Code Online (Sandbox Code Playgroud)

powershell foreach

15
推荐指数
1
解决办法
6万
查看次数

标签 统计

foreach ×1

powershell ×1