PowerShell调用Get-ChildItem访问网络匹配文件夹报错找不到路径如何解决
报错原因
- 核心语法问题:你使用
Select-Object FullName获取到的$allFolders数组元素并不是纯字符串格式的路径,而是包含FullName属性的PS自定义对象。直接将该对象传入Get-ChildItem -Path时,PowerShell会将对象默认序列化为@{FullName=你的路径}的字符串格式,系统会把这个字符串当成相对路径,结合JAMS作业默认的工作目录C:\WINDOWS\system32拼接出不存在的错误路径。 - 次要验证点:确认JAMS作业配置的运行身份账号,拥有对应网络共享路径的读取权限,避免权限类路径不存在报错。
修复方案
方案1:获取路径时直接展开为纯字符串
在Select-Object时加上-ExpandProperty参数,直接获取FullName属性的字符串值存入数组:
$Path = "\\myNetworkPath\myFolder" # 加-ExpandProperty直接拿到纯路径字符串 $allFolders = Get-ChildItem -Path $Path -Recurse -Directory -Filter "*myPattern" | Select-Object -ExpandProperty FullName foreach ($item in $allFolders){ $allFiles = Get-ChildItem -Path $item Write-Output $allFiles }
方案2:循环时显式调用FullName属性
不改获取数组的逻辑,循环时指定读取对象的FullName属性传入命令:
$Path = "\\myNetworkPath\myFolder" $allFolders = Get-ChildItem -Path $Path -Recurse -Directory -Filter "*myPattern" | Select-Object FullName foreach ($item in $allFolders){ # 显式取属性值 $allFiles = Get-ChildItem -Path $item.FullName Write-Output $allFiles }
方案3:省略Select步骤直接操作原始对象
Get-ChildItem返回的DirectoryInfo对象本身就可以直接传给Get-ChildItem的-Path参数,不需要单独选FullName:
$Path = "\\myNetworkPath\myFolder" # 不需要额外Select FullName $allFolders = Get-ChildItem -Path $Path -Recurse -Directory -Filter "*myPattern" foreach ($item in $allFolders){ $allFiles = Get-ChildItem -Path $item Write-Output $allFiles }
内容的提问来源于stack exchange,提问作者Khongor Bayarsaikhan
相关产品推荐
相关产品推荐

