在 PowerShell 代码中测试文件夹是否是连接点?

发布于 2024-08-22 06:30:11 字数 37 浏览 5 评论 0原文

如何在 PowerShell 代码中测试文件夹是否是连接点?

How can I test in PowerShell code if a folder is a junction point?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

池予 2024-08-29 06:30:11

至少从 PowerShell v5.0 开始,对链接有了更好的支持(或者 MS 称之为:重新分析点)

改进的 Item cmdlet - LinkType 属性

链接的文章位于 WMF 5.0 类别下,这可能意味着该方法自 PS v5.0 起可用。
这些功能包含在标准 Get-Item、Get-ChildItem 中,因此不需要额外的步骤。它可以在任何当前的 PS 上使用。

LinkType 是对象的字符串属性,由 Get-Item 和 Get-ChildItem 返回,
它可以具有以下四个值之一:''、'Junction'、'SymbolicLink'、'HardLink'。

要回答OP的问题,您可以使用以下方法检查文件夹是否是连接点:

if ((Get-Item -Path $Target -Force).LinkType -eq "Junction") { }

要检查文件/文件夹是否是任何类型的“ReparsePoint”(连接点、符号链接或硬链接):

if ((Get-Item -Path $Target -Force).LinkType) { }

普通文件/文件夹上的 LinkType 值是空字符串,在 PS 中用作 if 条件时解析为 False

Get-ChildItem 可用于列出所有 Junction 文件夹:

(Get-ChildItem -Path $Target -Force) | Where-Object { $_.LinkType -eq "Junction" }

请注意,文件或文件夹的“SymbolicLink”值相同,因此仅列出文件夹的符号链接:

(Get-ChildItem -Path $Target -Directory -Force) | Where-Object { $_.LinkType -eq "SymbolicLink" }

Cmdlet Get-ChildItem(别名:dir、ls、gci)现在显示 ReparsePoint 属性,如模式列中的 l,不带任何扩展名。但它不会显示“HardLink”,并显示 Junction 和 SymbolicLink 的 l

> Get-ChildItem -Path $Target -Force


    Directory: C:\Users


Mode                LastWriteTime         Length Name                          
----                -------------         ------ ----                          
d--hsl       2018-04-12     01:45                All Users                     
d-rh--       2018-05-09     06:12                Default                       
d--hsl       2018-04-12     01:45                Default User                  
d-----       2018-06-24     03:05                Papo                          
d-r---       2018-07-27     07:12                Public
  • LinkType 不适用于 \Users 和 \Users\ 内具有特殊权限的文件夹,即使上面看到的 Get-ChildItem 可以工作并在其上显示 l
  • 删除项目有问题。它无法删除 Junction,如果强制,将删除原始内容。据说这将在未来版本 PS v6 中得到修复。

使用这些改进的或今天的标准 Cmdlet,比以前的方法具有一些优势,如此处较旧的答案中所述。

  • 它确实区分了连接和符号链接
    如果OP想要测试文件夹是否是Junction,则通过属性属性检查将导致文件夹符号链接误报。

  • 检测到硬链接。

  • LinkType 是 [String],而不是 Attributes 属性,后者是 [FileAttributes] 类型,需要 .ToString() 或使用 -band

Since at least PowerShell v5.0, there is better support for links (or as MS calls them: Reparse Points)

improved Item cmdlets - LinkType property

Linked article is under WMF 5.0 category, which might mean that the method was available since PS v5.0.
These features were included in standard Get-Item, Get-ChildItem, so there are no additional steps required. It can be used on any current PS.

LinkType is a String property on an Object, returned by Get-Item and Get-ChildItem,
it can have one of the following four values: '', 'Junction', 'SymbolicLink', 'HardLink'.

To answer OP's question, you can check if a folder is a junction point using:

if ((Get-Item -Path $Target -Force).LinkType -eq "Junction") { }

To check if a file/folder is a "ReparsePoint", of any kind (Junction, SymbolicLink or HardLink):

if ((Get-Item -Path $Target -Force).LinkType) { }

LinkType value on ordinary file/folder is an empty String, which when used as if condition in PS resolves to False

Get-ChildItem can be used to list all Junction folders:

(Get-ChildItem -Path $Target -Force) | Where-Object { $_.LinkType -eq "Junction" }

Note that value 'SymbolicLink' is the same for both file or folder, so to list only Symbolic links to folders:

(Get-ChildItem -Path $Target -Directory -Force) | Where-Object { $_.LinkType -eq "SymbolicLink" }

Cmdlet Get-ChildItem (alias: dir, ls, gci) now shows ReparsePoint attribute, as l in Mode column, without any extension. But it will not show 'HardLink' and shows l for both Junction and SymbolicLink:

> Get-ChildItem -Path $Target -Force


    Directory: C:\Users


Mode                LastWriteTime         Length Name                          
----                -------------         ------ ----                          
d--hsl       2018-04-12     01:45                All Users                     
d-rh--       2018-05-09     06:12                Default                       
d--hsl       2018-04-12     01:45                Default User                  
d-----       2018-06-24     03:05                Papo                          
d-r---       2018-07-27     07:12                Public
  • LinkType does not work on folders with special permissions inside \Users and \Users\, even though Get-ChildItem as seen above does work and shows l on them.
  • Remove-Item has issues. It can't remove Junction, and if Forced, will remove original contents with it. This is said to be fixed in future version PS v6

Using these improved, or today's standard Cmdlets, has some advantages over previous methods, described in older answers here.

  • It does differentiate between Junction and Symbolic Link
    If OP wanted to test if folder is a Junction, checking by Attribute property would result in false positive for folder Symbolic Link.

  • detects Hard Link.

  • LinkType is [String] as opposed to Attributes property, which is [FileAttributes] type and needs .ToString() or a use of -band

负佳期 2024-08-29 06:30:11

If (Get-Item 测试文件夹).Attributes.ToString().Contains("ReparsePoint"){代码}

If (Get-Item Test Folder).Attributes.ToString().Contains("ReparsePoint"){Code}

棒棒糖 2024-08-29 06:30:11

看看这个博客:
https:// /web.archive.org/web/20190422210654/https://devblogs.microsoft.com/powershell/viewing-junctions-with-dir/

方法是复制内置文件系统格式化文件,修改它以便指示连接,然后使用 Update-FormatData 加载它:

来自博客:

文件系统格式化规则是
$pshome\FileSystem.Format.ps1xml 中。我
复制这个,然后在元素中
[ViewDefinitions –>查看->表格控件 –> TableRowEntries –> TableRowEntry –>表列项 –>表列项]
我改变了内容
值为“Mode”的 PropertyName
到以下内容:

; 
   “$($_.Mode)$(if($_.Attributes -band [IO.FileAttributes]::ReparsePoint)
{'J'})"  

这对
DirectoryInfo 对象属性
属性 ($_.Attributes)
.Net System.IO.FileAttributes.ReparsePoint
枚举值。如果结果不为零,
它在另一个旁边显示一个“J”
文件模式属性。接下来,加载
新的格式化文件如下:

<前><代码> PS>更新-FormatData -PrependPath myFilesystem.format.ps1xml

PrependPath 参数确保
新的格式化文件已加载
在内置格式化文件之前。

目录 alink 的模式中有一个“J”
专栏,似乎有效!

它位于模式列 J 中
交界处。

Take a look at this blog:
https://web.archive.org/web/20190422210654/https://devblogs.microsoft.com/powershell/viewing-junctions-with-dir/

the way to do it is to copy the built in file system formatting file, modify it so that junctions are indicated, then load it with Update-FormatData:

From the Blog:

The file system formatting rules are
in $pshome\FileSystem.Format.ps1xml. I
copied this, then in the element
[ViewDefinitions –> View –> TableControl –> TableRowEntries –> TableRowEntry –> TableColumnItems –> TableColumnItem]
I changed the content
of PropertyName with value of 'Mode'
to the following:

<ScriptBlock> 
   "$($_.Mode)$(if($_.Attributes -band [IO.FileAttributes]::ReparsePoint)
{'J'})" </ScriptBlock> 

This does a bitwise AND on the
DirectoryInfo object Attributes
property ($_.Attributes) against the
.Net System.IO.FileAttributes.ReparsePoint
enum value. If the result is not zero,
it displays a ‘J’ next to the other
file mode attributes. Next, load the
new formatting file like this:

 PS> Update-FormatData -PrependPath myFilesystem.format.ps1xml

The PrependPath parameter ensures that
the new formatting file is loaded
before the built-in formatting files.

Directory alink has a ‘J’ in the mode
column, seems to work!

It's in the Mode column J for
Junction.

美羊羊 2024-08-29 06:30:11

仅供参考,如果您碰巧正在运行 PowerShell 社区扩展,此信息可作为输出(以及注释属性) )在 Get-ChildItem 的输出上:

21> gci .\Roaming\Microsoft\eHome


    Directory: Microsoft.PowerShell.Core\FileSystem::C:\Users...


Mode           LastWriteTime       Length Name
----           -------------       ------ ----
d----     2/15/2010 12:18 AM        <DIR> DvdCoverCache
d----      8/9/2009  1:10 AM    <SYMLINK> DvdInfoCache [\...
d----      8/8/2009 11:51 PM        <DIR> DvdInfoCache.orig
d----    10/22/2009  7:12 PM        <DIR> mcl_images

但是,对于编程访问,我将按照其他海报的建议通过 Attributes 属性访问信息。

FYI, if you happen to be running PowerShell Community Extensions, this info is available as output (and as a note property) on output of Get-ChildItem:

21> gci .\Roaming\Microsoft\eHome


    Directory: Microsoft.PowerShell.Core\FileSystem::C:\Users...


Mode           LastWriteTime       Length Name
----           -------------       ------ ----
d----     2/15/2010 12:18 AM        <DIR> DvdCoverCache
d----      8/9/2009  1:10 AM    <SYMLINK> DvdInfoCache [\...
d----      8/8/2009 11:51 PM        <DIR> DvdInfoCache.orig
d----    10/22/2009  7:12 PM        <DIR> mcl_images

However for programmatic access I would access the info via the Attributes property as the other poster suggests.

又爬满兰若 2024-08-29 06:30:11

如果您拥有我推荐的 PowerShell 社区扩展(如果您正在使用联结),您可以执行以下操作来确定文件夹是否是联结:

Import-Module pscx
if ((Get-Item *test_folder*).ReparsePoint){
    Write-Host "YES"
}

If you have the PowerShell Community Extensions which I would recommend if you are working with junctions you can do the following to determine if a folder is a junction or not:

Import-Module pscx
if ((Get-Item *test_folder*).ReparsePoint){
    Write-Host "YES"
}
儭儭莪哋寶赑 2024-08-29 06:30:11

试试这个:

$TargetAttributes = (Get-Item -Path $Target -Force).Attributes.ToString()
if ($TargetAttributes -match "ReparsePoint") {
    if ($TargetAttributes -match "Archive") {
        Write-Output ("Link to a file.")
    } else {
        Write-Output ("Link to a folder.")
    }
} else {
    Write-Output ("Normal File or Folder.")
}    

Try this:

$TargetAttributes = (Get-Item -Path $Target -Force).Attributes.ToString()
if ($TargetAttributes -match "ReparsePoint") {
    if ($TargetAttributes -match "Archive") {
        Write-Output ("Link to a file.")
    } else {
        Write-Output ("Link to a folder.")
    }
} else {
    Write-Output ("Normal File or Folder.")
}    
朮生 2024-08-29 06:30:11

从列表中排除 Junction 的示例(或“-match”,用于排除所有其他):

(Get-ChildItem -Force | where {$_.PSIsContainer -eq $true -And $_.Attributes -notmatch "Reparse"})

Example for exclude Junction from listing (or "-match", for exclude all another):

(Get-ChildItem -Force | where {$_.PSIsContainer -eq $true -And $_.Attributes -notmatch "Reparse"})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文