我在另一篇文章中遇到了这段代码,它几乎满足了我的需要,但不知道如何修改它来查找特定的文件类型,即 *.bak、.txt 等。我正在使用 Powershell 和 [System .IO.DirectoryInfo] 因为,就像其他人所说的那样,使用 Get-ChildItem 在网络上太慢了。我认为这只是 $fileEntries = [IO.Directory]::GetFiles("C:\", " .bak") 之类的东西,但它仍然返回每个目录中的每个文件。--PS/.NET新手
try
{
$fileEntries = [IO.Directory]::GetFiles("C:\")
[System.IO.DirectoryInfo]$directInf = New-Object IO.DirectoryInfo("C:\")
$folders = $directInf.GetDirectories()
}
catch [Exception]
{
$_.Exception.Message
$folders = @()
}
foreach($fileName in $fileEntries)
{
#[Console]::WriteLine($fileName);
}
Remove-Variable -ErrorAction SilentlyContinue -Name fileEntries
foreach($folder in $folders)
{
recurse("C:\" + $folder + "\")
}
Run Code Online (Sandbox Code Playgroud)
这将循环遍历每个扩展,搜索根目录和子目录中的所有文件。确保您对所有目录拥有正确的权限,尤其是当您以根用户身份从 C:\ 运行时。
$Extensions = @(".bak",".csv",".txt")
Foreach ( $Extension in $Extensions )
{
[System.IO.Directory]::EnumerateFiles("C:\","*$Extension","AllDirectories")
}
Run Code Online (Sandbox Code Playgroud)
此方法仅适用于运行 .Net 4.0 或更高版本的 Powershell。检查并更新 .Net 版本:
$PSVersionTable
Name Value
---- -----
CLRVersion 2.0.50727.4971
BuildVersion 6.1.7600.16385
PSVersion 2.0
WSManStackVersion 2.0
PSCompatibleVersions {1.0, 2.0}
SerializationVersion 1.1.0.1
PSRemotingProtocolVersion 2.1
Run Code Online (Sandbox Code Playgroud)
CLRVsion 值是 .net 版本。
更新配置文件如下:
$Config = @"
<?xml version="1.0"?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0.30319"/>
<supportedRuntime version="v2.0.50727"/>
</startup>
</configuration>
"@
$Config > $PSHOME\Powershell.exe.config
Run Code Online (Sandbox Code Playgroud)
重新启动 Powershell 会话并验证 $PSVersionTable 变量中的 CLRVsion 值。
归档时间: |
|
查看次数: |
31383 次 |
最近记录: |