我想编写一个小脚本来搜索确切的文件名,而不是文件名中的字符串.
例如,如果我使用资源管理器搜索"主机",默认情况下会得到多个结果.使用脚本我只想要我指定的名称.我假设它有可能吗?
我只是真正开始编写脚本而且它仅供我个人使用,所以它并不重要,它只是让我烦恼.我有几个驱动器,所以我开始使用2个输入,一个用于查询驱动器号,另一个用于指定文件名.我可以通过扩展名,文件大小等进行搜索,但似乎无法将搜索固定到确切的名称.
任何帮助,将不胜感激!
编辑:感谢所有回复.只是为了更新.我在我的小脚本中添加了一个答案,效果很好.所有三个反应都有效,但我最终只能使用一个,而不是另外两个.干杯.只是为了澄清,'npp'是Notepad ++的别名,一旦找到就打开文件.
$drv = read-host "Choose drive"
$fname = read-host "File name"
$req = dir -Path $drv -r | Where-Object { !$PsIsContainer -and [System.IO.Path]::GetFileNameWithoutExtension($_.Name) -eq $fname }
set-location $req.directory
npp $req
Run Code Online (Sandbox Code Playgroud)
Mur*_*rph 64
在powershell提示符下,使用gci
cmdlet(别名Get-ChildItem
)和-filter
选项:
gci -recurse -filter "hosts"
Run Code Online (Sandbox Code Playgroud)
这将返回与文件名" hosts
" 的完全匹配.
SteveMustafa指出当前版本的powershell你可以使用-File
交换机给出以下内容来递归搜索名为" hosts
"的文件(而不是目录或其他杂项文件系统实体):
gci -recurse -filter "hosts" -File
Run Code Online (Sandbox Code Playgroud)
命令可能会打印许多红色错误消息,如" Access to the path 'C:\Windows\Prefetch' is denied.
".
如果要避免错误消息,请将其-ErrorAction
设置为静默.
gci -recurse -filter "hosts" -File -ErrorAction SilentlyContinue
Run Code Online (Sandbox Code Playgroud)
另一个帮助是您可以设置root来搜索使用-Path
.结果命令搜索显式搜索,例如,C驱动器的根将是
gci -Recurse -Filter "hosts" -File -ErrorAction SilentlyContinue -Path "C:\"
Run Code Online (Sandbox Code Playgroud)
Geo*_*rth 12
假设您有一个Z:
映射的驱动器:
Get-ChildItem -Path "Z:" -Recurse | Where-Object { !$PsIsContainer -and [System.IO.Path]::GetFileNameWithoutExtension($_.Name) -eq "hosts" }
Run Code Online (Sandbox Code Playgroud)
我使用这种形式就是这样的事情:
gci . hosts -r | ? {!$_.PSIsContainer}
Run Code Online (Sandbox Code Playgroud)
.
映射到位置参数Path
,"hosts"映射到位置参数Filter
.我强烈建议使用Filter
过Include
,如果提供商支持过滤(和文件系统提供程序).它比它好一点Include
.
我正在根据@Murph 的回答使用此功能。它在当前目录中搜索并列出完整路径:
function findit
{
$filename = $args[0];
gci -recurse -filter "*${filename}*" -file -ErrorAction SilentlyContinue | foreach-object {
$place_path = $_.directory
echo "${place_path}\${_}"
}
}
Run Code Online (Sandbox Code Playgroud)
用法示例: findit myfile
归档时间: |
|
查看次数: |
76796 次 |
最近记录: |