如何查找文件包含名称中的字符

时间:2014-02-12 20:57:58

标签: .net powershell

我正在搜索名称中包含特定字符的文件。找到后,文件名和路径将写在文本文件中。

$filePath = "c:", "d:"
$fileName = "~"
$computerName = Get-Content env:computername
$srvPath = "\\server\share$\FindFileScript\$computerName.txt"

#SEARCH FOR FILE ON C DISK
$fileResult = (Get-ChildItem -Recurse -Force $filePath -ErrorAction SilentlyContinue
| Where-Object { $_.Name -like "*$fileName*" } | Select-Object FullName | format-Table * -AutoSize)
if ($fileResult -eq $Null)
{
Write-Host "File named $fileName on disk C was not found."
}
Else
{
Write-Host "File named $fileName on disk C was found."
Out-File -FilePath $srvPath -InputObject $fileResult
}

2 个答案:

答案 0 :(得分:1)

这是我发现的一些代码更好的代码。

cls
write-Host "---------------------------------------------" -ForegroundColor Yellow
$filePath = Read-Host "Please Enter File Path to Search" 
write-Host "---------------------------------------------" -ForegroundColor Red
$fileName = Read-Host "Please Enter File Name to Search" 
write-Host "---------------------------------------------" -ForegroundColor Yellow
"`n" 

Get-ChildItem -Recurse -Force $filePath -ErrorAction SilentlyContinue | Where-Object { ($_.PSIsContainer -eq $false) -and  ( $_.Name -like "*$fileName*") } | Select-Object Name,Directory| Format-Table -AutoSize * 

write-Host "------------END of Result--------------------" -ForegroundColor Magenta 

# end of the script

答案 1 :(得分:0)

为什么不让它变得非常简单

gci -re -in "*~*" | %{ $_.FullName } | out-file $srvPath