22

I'm working with PowerShell, running a script (from my console) that includes this line:

$inpath = "C:\users\xxxxx\path\foo\bar"

and I keep getting this error:

Get-Content : Access to the path 'C:\users\xxxxx\path\foo\bar' is denied.
At C:\users\xxxxx\path\foo\testscript.ps1:53 char:12
+ Get-Content <<<<  $txtfile | Get-WordCount -Exclude (Get-Content c:\temp\exclude.txt) | select -First 15
    + CategoryInfo          : PermissionDenied: (C:\users\xxxxx\path\foo\bar:String) [Get-Content], UnauthorizedAcc
   essException
    + FullyQualifiedErrorId : GetContentReaderUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetContentCommand

The scripts and target files are all located on my local drive. I can access the files in Explorer, view/edit/save them using NotePad, and do not have any permissions restrictions set. When I'm on the command line, I can run the get-content cmdlet successfully on files in my path. I can change directories PS C:> cd C:\users\xxxxx\path\foo\bar and successfully list what's there. Even more interesting, I can duplicate the line that's erroring in the script, and NOT receive an error on the command line.

PS C:\users\xxxxx\path\foo> $inpath = "C:\users\xxxxx\path\foo\bar"
PS C:\users\xxxxx\path\foo>

This makes me suspect that the 'Permission Denied' error is actually something else, or something vague enough that I've got no clue how to proceed with troubleshooting. Is it possible for PS to have different permissions than the user under which it's running? Has anyone seen this behavior before, and how did you solve the problem? I'm sure there's a simple solution that I don't know.

4

3 回答 3

45
Get-Content :拒绝访问路径“C:\users\xxxxx\path\foo\bar”。
在 C:\users\xxxxx\path\foo\testscript.ps1:53 char:12

该路径看起来不像是文件,而是文件夹。

您确定要将文件名附加到文件夹并将其传递给Get-Content吗?

当您尝试像打开文件一样打开目录而不传递额外标志时,Windows 会拒绝访问;并且 .NET 不会传递这些标志(打开文件夹有一些特定情况,但它们不适用于此处)。

于 2013-01-23T16:22:51.937 回答
4

Get-Content 读取文件而不是文件夹的内容。请添加. 在您的文件夹路径之后,如下所示。

Get-Content "D:\Logs\*.*" | ?{($_|Select-String "test")}

如果你想通过它下面的所有文件夹,然后添加 -recurse 如下:

Get-Content "D:\Logs\*.*" -Recurse | ?{($_|Select-String "test")}
于 2015-01-06T20:38:24.147 回答
0

而不是这个:(根据您的评论)

foreach ($doc in $inpath) { do-function }

尝试这个:

foreach ($doc in (gci $inpath)) { do-function }

您正在foreach对字符串对象而不是文件夹项目执行操作。

于 2013-01-23T20:27:26.607 回答