检查指定目录的Powershell脚本

问题描述 投票:0回答:1

为什么这不起作用?我尝试通过询问 ChatGPT 来修复它,但它仍然没有给出正确的答案

如何编写一个 PowerShell 脚本来检查指定目录中是否有大于 1 GB 的文件,将这些文件的名称和大小记录到日志文件中,并删除超过 30 天的文件?提供示例脚本。

# Define the directory to check and the log file path
$directory = "C:\Path\To\Directory"
$logFile = "C:\Path\To\LogFile.txt"

# Get the current date
$currentDate = Get-Date

# Open the log file for writing
$logFileStream = [System.IO.StreamWriter]::new($logFile, $true)

# Write the header to the log file
$logFileStream.WriteLine("Log Date: $currentDate")
$logFileStream.WriteLine("Files larger than 1 GB:")

# Get all files in the specified directory
$files = Get-ChildItem -Path $directory -File

foreach ($file in $files) {
    # Check if the file size is greater than 1 GB (1 GB = 1,073,741,824 bytes)
    if ($file.Length -gt 1GB) {
        # Log the file name and size
        $logFileStream.WriteLine("File: $($file.FullName) - Size: $($file.Length / 1GB) GB")
        
        # Check if the file is older than 30 days
        $fileAge = ($currentDate - $file.LastWriteTime).Days
        if ($fileAge -gt 30) {
            # Delete the file
            Remove-Item -Path $file.FullName -Force
            # Log the deletion
            $logFileStream.WriteLine("Deleted: $($file.FullName) - Age: $fileAge days")
        }
    }
}

# Close the log file stream
$logFileStream.Close()

powershell
1个回答
0
投票

第 1 步:Verkrijg de servernaam

$server = (获取计算机信息).CsName

© www.soinside.com 2019 - 2024. All rights reserved.