get-childitem在脚本中运行时不填充变量,从PS控制台正常工作

时间:2013-11-17 17:11:28

标签: powershell powershell-v2.0 heisenbug

我正在尝试获取共享上的子目录列表,以下在我在控制台上进行测试时工作正常但在使用脚本运行时似乎没有填充我的$ folderList变量:

$pathInfo = "\\defiant\testShare"
$folderList = get-childitem $pathInfo | where-object { $_.PSIsContainer } | ForEach-Object { $_.FullName }
foreach($folder in $folderList) { write-host $folder }

当我在路径上运行这个确切的代码时,我知道它有子目录 当我通过.ps1运行时,$ folderList返回null,当通过控制台运行时,我按预期获得所有子目录的完整路径。

控制台输出(正常):

PS C:\windows\system32> $path = "\\defiant\testShare"
_________________________________________________________________________________________________ 
PS C:\windows\system32> $folderList = gci $path | ? { $_.PSIsContainer } | % { $_.FullName }
_________________________________________________________________________________________________ 
PS C:\windows\system32> foreach($folder in $folderList) { write-host $folder } 
\\defiant\testShare\testFolder

文件输出(损坏):

PS C:\windows\system32> C:\Users\testUser\Documents\PSScripts\test.ps1 

_________________________________________________________________________________________________

1 个答案:

答案 0 :(得分:0)

在@()中包含GCI语句似乎解决了我的问题:

$folderList = @(gci $pathInfo | ? { $_.PSIsContainer } | % { $_.FullName })

这是前同事提出的建议。