获取内容:无法找到路径

问题描述 投票:1回答:3

我正在尝试在PowerShell中编写一个脚本,该脚本在“foreach”循环中读取特定文件夹中包含“example”的所有文件。问题是我试图在变量中保存每个文件的内容而没有任何成功。尝试使用Get-Content $文件,它会抛出以下错误“Get-Content:找不到路径”,即使路径设置在文件夹var的开头,文件实际上包含我需要的文件。我无法将其分配给$ FileContent

$Folder = Get-ChildItem U:\...\Source

foreach($file in $Folder)
{
    if($file.Name -Match "example")
    {
        $FileContent = Get-Content $file                
    }
}
file powershell path save
3个回答
7
投票

发生这种情况是因为FileInfo对象的默认行为只返回文件的名称。也就是说,没有路径信息,因此Get-Content尝试从当前目录访问该文件。

使用FileInfo的FullName属性来使用绝对路径。像这样,

foreach($file in $Folder)
{
...
    $FileContent = Get-Content $file.FullName

1
投票

将您的工作目录更改为U:\...\Source然后它将工作。

使用

cd U:\...\Source
$folder = gci U:\...\Source

完成工作后,可以使用cd命令或push-location cmdlet再次更改工作目录。


0
投票

试试这个:

Get-ChildItem U:\...\Source -file -filter "*example*" | %{

$FileContent = Get-Content $_.fullname

}
© www.soinside.com 2019 - 2024. All rights reserved.