I am in the middle of trying to create a PowerShell script that will run automatically when my hard drive is full to a certain amount.
The script will read paths from a text document saved to C:\paths2.txt, this will allow me to add or delete paths later.
This is what I have come up with at the bottom if you can take a look. When the script is run using pdq deploy in noninteractive mode I get:
"Windows PowerShell is in NonInteractive mode. Read and Prompt functionality is not available. At C:\Windows\AdminArsenal\PDQDeployRunner\service-4\exec\Error Handling Wrapper.ps1:58 char:2
I tested it in interactive mode and see that I get a prompt saying:
Confirm The item at Microsoft.PowerShell.Core\FileSystem::C:\LocalSlaveData\O has children and the Recurse parameter was not specified. If you continue, all children will be removed with the item. Are you sure you want to continue? [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):
How can I change it so all commands are forced even the children folders like it's asking? I put force in all my commands so I'm not sure why it's giving a prompt.
Thanks for your help in advance
# Check if free space on local disk C is less than 20%
$disk = Get-WmiObject -Class Win32_LogicalDisk -Filter "DeviceID='C:'"
$freeSpaceGB = [math]::Round(($disk.FreeSpace / 1GB), 2)
$percentFree = [math]::Round(($disk.FreeSpace / $disk.Size) * 100, 2)
if ($percentFree -gt 20) {
Write-Host "Free space on local disk C is greater than 20%. Script will exit."
Exit
}
# Read the list of paths to delete files from the paths.txt file
$paths = Get-Content "C:\paths2.txt"
# Loop through each path and delete files that are more than 3 days old
$totalDataDeleted = 0
foreach ($path in $paths) {
$files = Get-ChildItem $path -Recurse -Force | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-3) }
$dataDeleted = ($files | Measure-Object -Property Length -Sum).Sum
$totalDataDeleted += $dataDeleted
$files | Remove-Item -Force
}
# Display the total amount of data deleted in GB
$totalDataDeletedGB = [math]::Round(($totalDataDeleted / 1GB), 2)
Write-Host "$totalDataDeletedGB GB of data has been deleted."