Get-Content : Cannot find path

隐身守侯 提交于 2019-12-08 04:18:22

问题


I'm trying to write a script in PowerShell which reads in a "foreach" loop all the only files in a specific folder which contains "example" in it's name. The problem is that I'm trying to save the content of each file in a variable without any success. Tried to use Get-Content $file and it throws the following error "Get-Content : Cannot find path" even though the path was set at the beginning to the Folder var and file actually contains the file that I need. I can't assign it to $FileContent

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

foreach($file in $Folder)
{
    if($file.Name -Match "example")
    {
        $FileContent = Get-Content $file                
    }
}

回答1:


This happens as the FileInfo object's default behavior returns just the file's name. That is, there is no path information, so Get-Content tries to access the file from current directory.

Use FileInfo's FullName property to use absolute path. Like so,

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



回答2:


Change your working directory to U:\...\Source and then it shall work.

Use

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

After you are done with your work, you can change your working directory again using cd command or the push-location cmdlet.




回答3:


try this:

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

$FileContent = Get-Content $_.fullname

}


来源:https://stackoverflow.com/questions/47922836/get-content-cannot-find-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!