How to make Get-ChildItem not follow links
I need Get-ChildItem
to return all files / folders inside the path. But there are also symbolic links to remote servers. Links are created:mklink /D link \\remote-server\folder
If I run Get-ChildItem -recurse
it follows the links to the remote servers and lists all files / folders from there. If I use -exclude it doesn't list the folder matching the excluded pattern, but it still goes down and lists all the included files and folders.
I really need to Get-ChildItem -recurse
ignore links and not follow them.
source to share
You can exclude links using the following command:
gci <your path> -Force -Recurse -ErrorAction 'silentlycontinue' |
Where { !($_.Attributes -match "ReparsePoint") }
After reading your comment: Can't you do it in two steps?
$excluded = @(gci <your path> -Force -Recurse -ErrorAction 'silentlycontine' | where { ($_.Attributes -match "ReparsePoint") )
get-childitem -path <your path> -recurse -exclude $excluded
source to share
Just the same thing was needed. He settled on ...
Function Get-ChildItemNoFollowReparse
{
[Cmdletbinding(DefaultParameterSetName = 'Path')]
Param(
[Parameter(Mandatory=$true, ParameterSetName = 'Path', Position = 0,
ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[String[]] $Path
,
[Parameter(Mandatory=$true, ParameterSetName = 'LiteralPath', Position = 0,
ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[Alias('PSPath')]
[String[]] $LiteralPath
,
[Parameter(ParameterSetName = 'Path')]
[Parameter(ParameterSetName = 'LiteralPath')]
[Switch] $Recurse
,
[Parameter(ParameterSetName = 'Path')]
[Parameter(ParameterSetName = 'LiteralPath')]
[Switch] $Force
)
Begin {
[IO.FileAttributes] $private:lattr = 'ReparsePoint'
[IO.FileAttributes] $private:dattr = 'Directory'
}
Process {
$private:rpaths = switch ($PSCmdlet.ParameterSetName) {
'Path' { Resolve-Path -Path $Path }
'LiteralPath' { Resolve-Path -LiteralPath $LiteralPath }
}
$rpaths | Select-Object -ExpandProperty Path '
| ForEach-Object {
Get-ChildItem -LiteralPath $_ -Force:$Force
if ($Recurse -and (($_.Attributes -band $lattr) -ne $lattr)) {
Get-ChildItem -LiteralPath $_ -Force:$Force '
| Where-Object { (($_.Attributes -band $dattr) -eq $dattr) -and '
(($_.Attributes -band $lattr) -ne $lattr) } '
| Get-ChildItemNoFollow -Recurse
}
}
}
}
Will print all children of the path (including symlinks / jumps), but will not follow symlinks / jumps when repeating.
Didn't need all the functions Get-ChildItem
, so don't write them down, but if you only need -Recurse
and / or -Force
, it's basically a replacement.
Tested (briefly) on PSv2 and PSv4 on Windows 7 and 2012. No guarantees, etc.
(PS: I hate Verb-Noun
these situations ...)
source to share