簡體   English   中英

Powershell -LiteralPath 帶通配符

[英]Powershell -LiteralPath with wildcard

由於文件名有方括號,我需要使用-LiteralPath 但是,通過這樣做,我失去了在代碼中使用通配符(包括任何文件擴展名)的能力:

$files = Get-ChildItem -Recurse -LiteralPath "$somepath"
foreach ($f in $files){
    Test-Path -LiteralPath "$somepath\$($f.BaseName).*" -PathType Leaf
}

其中一個文件是file1 [123].txt並且此文件的Test-Path失敗。 如何修復這種行為? 文件 [123].txt 的測試路徑失敗

正如@Wasif 所建議的: 建議的解決方案 1 建議的解決方案 2

請嘗試以下操作。

Test-Path 'file1 ``[123].*'
foreach ($f in $files){
    $path = "$somepath\$($f.BaseName).*".Replace('[', '``[')
    Test-Path -Path $path -PathType Leaf
}

而不是使用 "$somepath\\$($f.BaseName).*" 你可以直接使用 $files 變量本身的文件系統對象的完整路徑,即$files.FullName我希望下面的代碼適合你:)

$files = Get-ChildItem -Recurse -LiteralPath "$somepath"
$files | ForEach-Object {Test-Path -LiteralPath $_.FullName -PathType Leaf}

您剛剛關閉,只需將通配符部分放在 -Filter 參數中並刪除 -PathType

$files = Get-ChildItem -Recurse -LiteralPath "$somepath"
foreach ($f in $files){
    Test-Path -LiteralPath "$somepath" -Filter "$($_.BaseName).*"
}

但是您可以像這樣使用 -Path:

-Path `"$somepath\$($_.basename).*`"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM