Get-ChildItem -File 或 -Directory 在不同的用户上下文中不起作用

Get-ChildItem -File or -Directory doesn't work under different user context

我有一个包含以下行的 PowerShell cmdlet

$items = Get-ChildItem -Path $FolderName -File -Force |
         Sort CreationTime |
         Select -First 1 -Last 1

它在我的正常登录下工作正常,但如果我以域管理员身份登录我的计算机,我收到一条错误消息,告诉我 -File 未被识别为 Get-ChildItem 的有效参数。

我怀疑域管理员 运行 正在使用早期版本的 PowerShell,所以在两个帐户下我都有 运行 $PSVersionTable.PSVersion 并得到以下信息:

Major  Minor  Build  Revision
-----  -----  -----  --------
5      0      10586  117

如果有的话,我希望我的本地登录失败,而域管理员登录会由于权限差异而成功,但它似乎是相反的。

Get-ChildItem 会不会以某种方式在您的 $profile 或其他内容中被覆盖了?

你可以检查 Get-ChildItem 执行了什么,如果你 运行 这个:

get-command Get-ChildItem

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Cmdlet          Get-ChildItem                                      3.1.0.0    Microsoft.PowerShell.Management

如果它被这样的操作覆盖:

Function Get-ChildItem { }

然后会显示:

get-command Get-ChildItem

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Function        Get-ChildItem

如果是这种情况,您可以使用

删除自定义版本
Remove-Item Function:\Get-ChildItem

您也可以尝试不使用 -File 参数,而是自己过滤掉文件夹:

$items = Get-ChildItem -Path $FolderName -Force | 
    Where PSIsContainer -eq $False |
    Sort CreationTime |
    Select -First 1 -Last 1

可以通过确保将 PATH 和 PSModulePath 变量设置为包含 ps1 脚本的位置来解决该问题。

在此特定情况下,PATH 和 PSModulePath 变量包含第一个用户而非第二个用户的脚本位置。

通过更正此脚本,第 2 次用户登录成功 运行。