首先,在脚本编写方面,我是一个新手。到目前为止,我已经运行了脚本的前几行。我的日志文件输出为文本文件,但是我在创建switch语句时遇到麻烦,该语句继续通过按随机数来提示用户。任何帮助将不胜感激。
Clear-Host
$Dir = Get-ChildItem C:\Users\rtres\Downloads\ -Recurse
$List = $Dir | where {$_.Extension -eq ".log"} | Out-File 'C:\Users\rtres\Downloads\Log.txt'
Clear-Host
$Dir = Get-ChildItem C:\Users\rtres\Downloads\ -Recurse
$List = $Dir | where {$_.Extension -eq ".log"} | Out-File 'C:\Users\rtres\Downloads\Log.txt'
答案 0 :(得分:2)
刚接触PowerShell时,建议您阅读有关Get-ChildItem cmdlet的内容,以了解它返回的对象类型。
阅读代码,让我觉得您期望以字符串形式显示文件名列表,但实际上它是FileInfo和/或DirectoryInfo对象的列表。
话虽如此,创建一个循环来提示用户输入某个值并不难。试试这个:
# create variables for the folder to search through and the complete path and filename for the output
$folder = 'C:\Users\rtres\Downloads'
$file = Join-Path -Path $folder -ChildPath 'Log.txt'
# enter an endless loop
while ($true) {
Clear-Host
$answer = Read-Host "Press any number to continue. Type Q to quit."
if ($answer -eq 'Q') { break } # exit the loop when user wants to quit
if ($answer -match '^\d+$') { # a number has been entered
# do your code here.
# from the question, I have no idea what you are trying to write to the log..
# perhaps just add the file names in there??
# use the '-Filter' parameter instead of 'where {$_.Extension -eq ".log"}'
# Filters are more efficient than other parameters, because the provider applies them when
# the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved.
Get-ChildItem $folder -Recurse -File -Filter '*.log' | ForEach-Object {
Add-Content -Path $file -Value $_.FullName
}
}
else {
Write-Warning "You did not enter a number.. Please try again."
}
# wait a little before clearing the console and repeat the prompt
Start-Sleep -Seconds 4
}
希望有帮助