powershell - 如何使用 PowerShell 解析文件夹和文件?
问题描述
我正在尝试构建一个在特定文件夹和其中的日志文件中移动的脚本,并过滤错误代码。之后,它将它们传递到一个新文件中。
我不太确定如何使用 for 循环来做到这一点,所以我将在下面留下我的代码。
如果有人能告诉我我做错了什么,那将不胜感激。
$file_name = Read-Host -Prompt 'Name of the new file: '
$path = 'C:\Users\user\Power\log_script\logs'
Add-Type -AssemblyName System.IO.Compression.FileSystem
function Unzip
{
param([string]$zipfile, [string]$outpath)
[System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)
}
if ([System.IO.File]::Exists($path)) {
Remove-Item $path
Unzip 'C:\Users\user\Power\log_script\logs.zip' 'C:\Users\user\Power\log_script'
} else {
Unzip 'C:\Users\user\Power\log_script\logs.zip' 'C:\Users\user\Power\log_script'
}
$folder = Get-ChildItem -Path 'C:\Users\user\Power\log_script\logs\LogFiles'
$files = foreach($logfolder in $folder) {
$content = foreach($line in $files) {
if ($line -match '([ ][4-5][0-5][0-9][ ])') {
echo $line
}
}
}
$content | Out-File $file_name -Force -Encoding ascii
在 LogFiles 文件夹中还有另外三个文件夹,每个文件夹都包含日志文件。谢谢
解决方案
扩展上面关于递归文件夹结构的评论,然后实际检索文件的内容,您可以尝试以下内容:
$allFiles = Get-ChildItem -Path 'C:\Users\user\Power\log_script\logs\LogFiles' -Recurse
# iterate the files
$allFiles | ForEach-Object {
# iterate the content of each file, line by line
Get-Content $_ | ForEach-Object {
if ($_ -match '([ ][4-5][0-5][0-9][ ])') {
echo $_
}
}
}
推荐阅读
- matlab - 尝试使用 Maclaurin 系列使用持久函数估计正弦
- c++ - 如何在 C++ 中填充和取消填充 std::string?
- python - 使用海龟导入对角线打印形状
- javascript - 在两个 div 中的锚点中包装内容(包括文本节点)
- python - 为什么将变量与 0.0 进行比较会返回 false?
- javascript - 我怎样才能使它显示菜单上的所有内容而不必搜索?
- xamarin.forms - 如何使用 FFImageLoading 将动画 GIF 实现为启动画面
- lua - Lua 脚本在 TS3 解释中戳客户端
- javascript - 如何使用 JavaScript 设置 cookie?
- javascript - 如何使用 css-in-js 在悬停另一个元素时显示 div 元素?