右键运行PowerShell脚本时Get-ChildItem返回空值的原因
我在script.ps1中编写了以下代码:
$CurrentPath = $PSScriptRoot Write-Host "CurrentPath:" $CurrentPath $temp = Get-ChildItem -Path $CurrentPath -Recurse -Include bin,obj Write-Host "temp:" $temp
在命令行执行.\script.ps1时,控制台输出正常:$CurrentPath返回脚本文件路径,$temp返回符合条件的文件列表。但右键点击脚本文件选择「用PowerShell运行」时,$CurrentPath结果正常,$temp却为空。请问为何第二种场景下Get-ChildItem返回空值?
原因分析
右键「用PowerShell运行」脚本时,PowerShell的当前工作目录($PWD)并非脚本所在目录,而是默认的系统目录(如C:\Windows\System32或用户文档目录)。
而Get-ChildItem的-Include参数存在特性:当搭配-Recurse使用,但-Path参数末尾未添加通配符(*)时,它只会检查路径本身是否匹配-Include的条件,不会递归查找子目录内的匹配项。
简单来说,此时Get-ChildItem -Path $CurrentPath -Recurse -Include bin,obj会判断$CurrentPath这个路径本身是否名为bin或obj,显然不满足,因此返回空值。而命令行执行时,工作目录就是脚本所在目录,-Path默认指向当前目录,搭配-Recurse和-Include能正确递归查找子目录中的bin/obj。
解决方法
有两种可靠的修复方式:
方式1:给-Path添加通配符
修改Get-ChildItem的路径参数,在末尾加上\*,确保递归查找子目录:
$temp = Get-ChildItem -Path "$CurrentPath\*" -Recurse -Include bin,obj
方式2:先切换到脚本所在目录
在脚本开头将当前工作目录切换为脚本目录,再执行查找操作:
$CurrentPath = $PSScriptRoot Set-Location $CurrentPath $temp = Get-ChildItem -Recurse -Include bin,obj
两种方式都能保证无论用哪种方式运行脚本,都能正确找到bin和obj目录。
内容的提问来源于stack exchange,提问作者Goran

