我正在尝试构建一个 powershell 脚本,它将递归地遍历特定文件夹及其子文件夹以列出其中的所有文件。
此外,我想计算 MD5 和 SHA1 哈希值,以及 B 中的文件大小,并将结果导出到 CSV。
所以,每个文件,我需要:
我能够想出以下内容;
gci -Recurse -Exclude *.txt, *.ps1, *.csv | select FullName | %{get-Filehash -Algorithm md5 -Path $_.FullName ; get-FileHash -Algorithm sha1 -Path $_.FullName ; (Get-Item -Path $_.FullName).Length} | export-csv -Path $PSScriptRoot\md5hashes.csv -NoTypeInformation
在 Powershell 中,这看起来还不错,但在 .csv 中不包含文件大小。
非常感谢您提前抽出时间!
这是一个写入 xml 的脚本。 您可以用 CSV 替换 XML 代码
using assembly System.Xml
using assembly System.Xml.Linq
Function WriteTree
{
Param ([System.IO.DirectoryInfo]$info, [System.Xml.XmlWriter]$writer)
begin{
$size = [long]0;
$writer.WriteStartElement("Folder");
}
process{
try
{
$writer.WriteAttributeString('name', $info.Name);
$writer.WriteAttributeString('numberSubFolders', $info.GetDirectories().Count.ToString());
$writer.WriteAttributeString('numberFiles', $info.GetFiles().Count.ToString());
$writer.WriteAttributeString('date', $info.LastWriteTime.ToString());
foreach ($childInfo in $info.GetDirectories())
{
$size += WriteTree -info $childInfo -writer $writer;
}
}
catch
{
$errorMsg = [string]::Format("Exception Folder : {0}, Error : {1}", $info.FullName, $_);
Write-Host $errorMsg;
$writer.WriteElementString('Error', $errorMsg);
}
$fileInfo = $null;
try
{
$fileInfo = $info.GetFiles();
}
catch
{
$errorMsg = [string]::Format('Exception FileInfo : {0}, Error : {1}', $info.FullName, $_);
Write-Host $errorMsg;
$writer.WriteElementString('Error',$errorMsg);
}
if($fileInfo -ne $null)
{
foreach ($finfo in $fileInfo)
{
try
{
$writer.WriteStartElement('File');
$writer.WriteAttributeString('name', $finfo.Name);
$writer.WriteAttributeString('size', $finfo.Length.ToString());
$writer.WriteAttributeString('date', $info.LastWriteTime.ToString());
$writer.WriteEndElement();
$size += $finfo.Length;
}
catch
{
$errorMsg = [string]::Format('Exception File : {0}, Error : {1}', $finfo.FullName, $_);
Write-Host $errorMsg;
$writer.WriteElementString('Error', $errorMsg);
}
}
}
$writer.WriteElementString('size', $size.ToString());
$writer.WriteEndElement();
return $size;
}
end{}
}
$filename = 'c:\temp\test.xml'
$folder = 'c:\temp'
$writer = $null
$settings = [System.Xml.XmlWriterSettings]::new();
$settings.Indent = $true;
$writer = [System.Xml.XmlWriter]::Create($filename, $settings);
$writer.WriteStartDocument($true);
$info = [System.IO.DirectoryInfo]::new($folder);
WriteTree -info $info -writer $writer;
$writer.WriteEndDocument();
$writer.Flush();
$writer.Close();
Read-Host 'Enter Return'