我有一个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