PowerShell Script only works from PowerShell Console and not from ISE - powershell

I am very very new to PowerShell. I am trying to delete a set of Test Results files in folders through PowerShell. When I run the code through PowerShell console, it works. The same code doesn't work through ISE.
Below is the code :
Set-Location -Path "Path";
$testResultsFolder = Get-ChildItem -Include *TestResults -Recurse | ?{ $_.PSIsContainer } | Select-Object FullName;
$date = Get-Date;
$limit = 30;
foreach($testResult in $testResultsFolder)
{
$resultsPath = Get-Item $testResult.FullName;
Get-ChildItem -Path $resultsPath -Recurse -Force | Where-Object { -not $_.PSIsContainer -and $date.Subtract($_.LastWriteTime).Days -gt $limit } | Remove-Item -Force;
}
This works fine from PowerShell console but not from ISE. The ISE does not show any error. It says 'Completed'. Can somebody throw some light on what I am doing wrong?

Try this:
Delete.ps1
#Requires -Version 3
$Path = 'C:\Temp'
$Cleanup = (Get-ChildItem -Path $Path -Include '*TestResults' -Recurse -Directory).FullName
ForEach ($Folder in $Cleanup)
{
Get-ChildItem -Path $Folder -File -Recurse -Force |
Where-Object { $PSItem.LastWriteTime -lt (Get-Date).AddDays(-30) } |
Remove-Item -Force
}
Using Set-Location can result in inconsistent results, especially if you're using dynamic variables. I'd suggest using a variable target so you're getting consistent results.

Related

I am trying to get the files in zip format which were newly created around two days ago using powershell and I am not getting any output

$Servers = Get-content 'D:\utils\Backup\SBX servers.txt'
foreach($Path in $Servers){
$Path = "E:\Backup"
$result = Get-ChildItem E:\Backup\*_DB.zip -Recurse -Force -File |Format-Wide| Where-Object { $_.LastWriteTime -gt (get-date).AddDays(-1)}
$result
}
you were not far from the solution, but there are multiple problem with your syntax. First you should not "filter" (where-object), after "formating" (Format-wide).
foreach($Path in $Servers){
$Path = "E:\Backup"
$result = Get-ChildItem E:\Backup*DB.zip -Recurse -Force -File | Where-Object { $_.LastWriteTime -gt (get-date).AddDays(-1)}
$result | Format-Wide
}
you were missing the "underscore" in your filter too: "$." -> "$_."

nothing returned to variable when assigning to recursive gci search omitting folders using powershell v2

I am trying to recursively search for files on a windows 7 machine + network drives attached to it while excluding certain folders i.e. C:\windows & all recursive folders in this such as system32.
I know this question has been asked before but following the answers has not helped and I am still left with a blank variable.
Here are the combinations I have tried:
$AllDrives = Get-PSDrive
$files=#("*.xml",*.txt)
foreach ($Drive in $AllDrives) {
if ($Drive.Provider.Name -eq "FileSystem") {
$filenames = Get-ChildItem -recurse $drive.root -include ($files) -File | Where-Object {$_.PSParentPath -notlike "*Windows*" -and $_.PSParentPath -notlike "*Microsoft*"
}
}
I have also tried these combinations:
$filenames = Get-ChildItem -recurse $drive.root -include ($files) -File | Where-Object {$_.PSParentPath -notmatch "Program Files|Users|Windows"}
$exclude_pattern = $drive.root + "Windows"
$filenames = Get-ChildItem -Force -Recurse -path $drive.root -Include $files -Attributes !Directory+!System -ErrorAction "SilentlyContinue" | Where-Object { $_.PSIsContainer -eq $false } | Where-Object { $_.FullName -notmatch $exclude_pattern }
Unfortunately, after an amount of time has elapsed, when I type $filename into the terminal nothing has been assigned to it.

Log deleted files to a text file

I want to know how to log the actions from this script to a text file because I don't know how to do it as the cmdlet Start-Transcript doesn't work for me and I wasn't able to find a solution on the Internet.
The problem is that the Where-Object cmdlet doesn't output anything captured by Get-ChildItem.
Does anybody has a good idea to solve this?
$limit = (Get-Date).AddDays(-30)
$path = Split-Path -Parent $MyInvocation.MyCommand.Definition
Get-ChildItem -Path $path -Recurse -Force | Where-Object {
!$_.PSIsContainer -and
$_.LastWriteTime -lt $limit
} | Remove-Item -Force
Get-ChildItem -Path $path -Recurse -Force | Where-Object {
$_.PSIsContainer -and
(Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object {
!$_.PSIsContainer
}) -eq $null
} | Remove-Item -Force -Recurse
try something like this
$limit = (Get-Date).AddDays(-30)
$path =Split-Path -Parent $MyInvocation.MyCommand.Definition
Get-ChildItem $path -file -recurse -force | where LastWriteTime -lt $limit |
Tee-Object -FilePath "c:\temp\deleted.txt" -Append | Remove-Item
Get-ChildItem $path -directory |
where {(Get-ChildItem $_.FullName -file -Recurse | select -First 1) -eq $null} |
Tee-Object -FilePath "c:\temp\deleted.txt" -Append | Remove-Item
howdy error666,
you can use use a few different methods ...
Tee-Object = fork the stream to a file
-PipelineVariable = accumulate the info in a variable
use a loop = put a log-to-file step in it
put a ForEach-Object in the pipeline
that can both log your info and do the Remove-Item.
the loop is the easiest to understand. [grin] however, if you want to keep it in a pipeline, you could add a ForEach-Object where the Where-Object scriptblock is and put both the filter test and the various actions in that block.
take care,
lee

Powershell Cleanup script. Excluded folder not being excluded

I wrote a simple script that will run as a scheduled task every weekend. This script cleans up files older than # days and you can give the name of a folder for exclusion as a parameter. This folder should not be cleaned up by the script. But somehow the script still deletes some files from the excluded folder. But in a strange way no files matching the conditions of the parameter.
For example I run the script to delete files older than 15 days and exclude the folder NOCLEANUP. but some files still get deleted from that folder, but there are still files older than 15 days in the NOCLEANUP folder.
Code below
Thanks in advance and apologies for the dirty code. Still new to PS.
Function CleanDir ($dir, $days, $exclude, $logpath)
{
$Limit = (Get-Date).AddDays(-$days)
$Path = $dir
#Folder to exclude
$ToExclude = $exclude
#Log location
$Log= $logpath
$Testpath = Test-Path -PathType Container -Path $Log
if ($Testpath -ne $true)
{
New-Item -ItemType Directory -Force -Path $Log
}
#Logs deleted files
cd $Log
Get-ChildItem -Path $Path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.LastwriteTime -lt $Limit } | Where-Object { $_.fullname -notmatch $ToExclude} | Where-Object { $_.fullname -notmatch '$RECYCLE.BIN'} | Out-File -FilePath CLEANUPLOG.TXT
# Delete files older than the $Limit.
Get-ChildItem -Path $Path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.LastwriteTime -lt $Limit } | Where-Object { $_.fullname -notlike $ToExclude} | Remove-Item -Force -Recurse
#Goes into every folder separately and deletes all empty subdirectorys without deleting the root folders.
$Folder = Get-ChildItem -Path $Path -Directory
$Folder.fullname | ForEach-Object
{
Get-ChildItem -Path $_ -Recurse -Force | Where-Object {$_.PSIsContainer -eq $True} | Where-Object {$_.GetFiles().Count -eq 0} | Remove-Item -Force -Recurse
}
}

Invoking Powershell commands in a batch file

Can anybody help me please in writing the below Powershell commands as a batch file? I will execute the file by command prompt. I don't have the option of creating a ps1 file and executing it through the command prompt.
Thank you.
$limit = (Get-Date).AddDays(-4)
$path = "T:\FolderName"
Get-ChildItem -Path $path -Recurse -Force -include *.txt | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force
Get-ChildItem \\123.456.78.910\Y$\Z\*.txt | Where { $_.CreationTime -ge (Get-Date).AddMinutes(-30) } | % { Copy-Item $_.FullName -destination T:\FolderName }
You can invoke powershell.exe with the -command parameter to do this. You can also have more than one powershell command by separating them with semicolon. You should double-double-quote any double-quotes.
Here's an example:
powershell -command "$limit = (Get-Date).AddDays(-4); $path = 'T:\Folder Name';Get-ChildItem -Path $path -Recurse -Force -include *.txt | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force"
powershell -command "$limit = (Get-Date).AddDays(-4); $path = 'T:\Folder Name';Get-ChildItem \\123.456.78.910\Y$\Z\*.txt | Where-Object { $_.CreationTime -ge (Get-Date).AddMinutes(-30) } | % { Copy-Item $_.FullName -destination 'T:\DestinationFolderName' }"
EDIT:
Here is a one-line version of it with only a single set of ""; all quotes inside are single '
powershell -command "$limit = (Get-Date).AddDays(-2); $path = 'D:\Folder\Folder Name'; Get-ChildItem -Path $path -Recurse -Force -include *.txt | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force;Get-ChildItem \\123.456.25.123\D$\folder*.txt | Where-Object { $_.CreationTime -ge (Get-Date).AddMinutes(-30) } | % { Copy-Item $_.FullName -destination 'D:\Folder\Folder' }";