问题
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