为什么Get-ChildElement过滤的不同方法会给相同的对象实际上是不同的?

问题描述 投票:0回答:1

出于几个不相关的原因,在使用Get-ChildItem命令时,我正在使用多种方法来处理过滤管道输出。

我创建了一个简短的代码来说明我的意思。当我使用不同的方式获取同一项目时,即使发现每次都是同一项目,该项目也会根据发现方式的不同而被“字符串化”。

假设我们在其中有C:\Folder1\Folder1-aFile1.7z的文件夹File2.txtFile1-X中有更多Folder1文件夹,每个文件夹中都有.7z.txt文件,它们的名称可以包含一些特殊字符,例如方括号。这与这个问题无关,这就是为什么我更喜欢使用某种特定的过滤方式(原因见附件代码的注释)的原因。

这是说明我观点的代码:

#Initialize 7zip
if (-not (test-path "$env:ProgramFiles\7-Zip\7z.exe")) {throw "$env:ProgramFiles\7-Zip\7z.exe needed"}
set-alias 7zip "$env:ProgramFiles\7-Zip\7z.exe"

#this is a placeholder, $TXTFile would be the result of an iteration over a previous Item array
$TXTFile = Get-Item -Path "C:\Folder1\Folder1-a\File2.txt"

#Now there comes 3 different ways to select the 7z file in the same directory as File2.txt

# I use this to modify the path name so square brackets are properly escaped
$directory1 =$TXTFile.DirectoryName -replace "\[","`````[" -replace "\]","`````]"
[array]$7ZFile1 = Get-ChildItem -File -Path "$directory1\*.7z"

# This option uses LiteralPath so no modification is needed.
# More convenient since it supports any kind of special character in the name.
$directory2=$TXTFile.DirectoryName
[array]$7ZFile2= Get-ChildItem -File -LiteralPath $directory2 -Filter *.7z

# This option uses LiteralPath so no modification is needed.
# More convenient since it supports any kind of special character in the name.
$directory3=$TXTFile.DirectoryName
[array]$7ZFile3 = Get-ChildItem -File -LiteralPath $directory3 | Where-Object {$_.Extension -eq ".7z"}

#Lets see each item. They all seem equal
$7ZFile1
$7ZFile2
$7ZFile3
Write-Host "`n"

#Lets see how they have he same FullName
Write-Host $7ZFile1.FullName
Write-Host $7ZFile2.FullName
Write-Host $7ZFile3.FullName
Write-Host "`n"

#Lets compare them using -eq. Damn, they are not equal
if($7ZFile1 -eq $7ZFile2){"7ZFile1=7ZFile2"}Else{"7ZFile1!=7ZFile2"}
if($7ZFile2 -eq $7ZFile3){"7ZFile2=7ZFile3"}Else{"7ZFile2!=7ZFile3"}
if($7ZFile3 -eq $7ZFile1){"7ZFile3=7ZFile1"}Else{"7ZFile3!=7ZFile1"}
Write-Host "`n"

#This is relevant if we "stringify" each object. First one returns FullName, the two others return Name
Write-Host $7ZFile1
Write-Host $7ZFile2
Write-Host $7ZFile3
Write-Host "`n"

#Example of this being relevant. Inside File1.7z is a txt file. If you use 7zip por example like this:
7zip t $7ZFile1 *.txt -scrc     #Success
7zip t $7ZFile2 *.txt -scrc     #Fail, can't find 7ZFile2
7zip t $7ZFile3 *.txt -scrc     #Fail, can't find 7ZFile3

我正在使用$7ZFile.FullName始终获得所需的字符串,但是我想知道为什么会这样?为什么首先会有区别?

出于几个不相关的原因,在使用Get-ChildItem命令时,我正在使用几种方法来过滤管道输出。我创建了一个简短的代码来说明我的意思。当我...

powershell filtering get-childitem
1个回答
0
投票

这是PS 5中的常见烦恼,其中get-childitem返回的字符串版本没有完整路径。在更高版本的PS中已更改。

© www.soinside.com 2019 - 2024. All rights reserved.