i am using following powershell script for getting folder with latest time stamp
$drive = get-psdrive |select root |Select-String -InputObject {$_.Root} -Pattern ':'
Write-Host $drive
foreach ($a in $drive)
{
Get-ChildItem -Path $a -Filter "*sysout" -Recurse -Force -ErrorAction SilentlyContinue|select -last 1
}
}
it gives following output
A:\ C:\ D:\ E:\ F:\ G:\ H:\ I:\ J:\ K:\ Z:\
Directory: E:\utility
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 2/21/2018 2:06 AM sysout
Directory: F:\
Mode LastWriteTime Length Name
---- ------------- ------ ----
d---- 2/21/2018 3:15 AM sysout
i need latest timestamp folder but using -last 1 doesnt give desired results.
Last doesn't really have any meaning without order.
Get-ChildItem -Path $a -Filter "*sysout" -Recurse -Force -ErrorAction SilentlyContinue |
Sort-Object LastWriteTime -Descending |
Select-Object -Last 1
Related
The following piece of code works, but only for today's date. What do I have to change to put in a specific date, e.g. the 3rd of May 2022? I also want to do that with a Read-Host.
Get-ChildItem -Path C:\test\testdir -Include *.txt, *.log -Recurse |
Where-Object LastWriteTime -ge ([datetime]::Today) |
Sort-Object LastWriteTime |
Select-String -Pattern Test
(get-item "C:\tmp\test.xml").lastwritetime.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True DateTime System.ValueType
The datatype is DateTime, so no need to build matching strings.
In regards to the requirement to use read-host you could do:
[datetime]$DateTime = read-host
By doing so you cast the Input as DateTime but this requires that you enter a supported format. I think its easier if you have to specify the days back to calculate the DateTime information, e.g.;
[int]$daysBack = read-host
Get-ChildItem -Path C:\test\testdir -Include *.txt, *.log -Recurse |
Where-Object LastWriteTime -ge (get-date).AddDays(-$daysback) |
Sort-Object LastWriteTime |
Select-String -Pattern Test
I am trying to get the target files from a folder with many .lnk shortcuts and put them in a new folder using Powershell. I have the following script and it runs but the output folder does not show anything:
$WScript = New-Object -ComObject WScript.Shell
Get-ChildItem -Path "<shortcut folder>*.lnk" | ForEach-Object {$WScript.CreateShortcut($_.FullName).TargetPath} | Out-File -FilePath "<Destination Folder>"
Branching off my comment to you. YOu can't Out-File a string, which is what is in the target path. It's not a real file. You can OUt-File that string to a text file if that is what you need, but that does not sound like what you are after.
Just step through each segment to make sure you are getting what you'd expect and use that target in a copy statement.
# Validate the lnk data
$WScript = New-Object -ComObject WScript.Shell
Get-ChildItem -Path "$env:USERPROFILE\Desktop\ClearIEData.lnk" | Format-Table -AutoSize
<#
# Results
Directory: C:\Users\postanote\Desktop
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 28-Oct-18 00:52 1293 ClearIEData.lnk
#>
# Extract the lnk target path
$WScript = New-Object -ComObject WScript.Shell
Get-ChildItem -Path "$env:USERPROFILE\Desktop\ClearIEData.lnk" |
ForEach-Object {$WScript.CreateShortcut($_.FullName).TargetPath}
<#
# Results
D:\Tools\ClearIEData.cmd
#>
# Take needed action on the lnk target path info
$WScript = New-Object -ComObject WScript.Shell
Get-ChildItem -Path "$env:USERPROFILE\Desktop\ClearIEData.lnk" |
ForEach-Object {
Copy-Item -Path $($WScript.CreateShortcut($_.FullName).TargetPath) -Destination 'D:\temp' -WhatIf
}
<#
# Results
What if: Performing the operation "Copy File" on target "Item: D:\Tools\ClearIEData.cmd Destination: D:\temp\ClearIEData.cmd".
#>
If satisfied with the results, comment out or remove the -WhatIf and run the code again to take the action.
Get-ChildItem -Path 'D:\temp' -Filter 'ClearIEData.cmd'
<#
# Results
Directory: D:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 05-Mar-20 15:10 2571 ClearIEData.cmd
#>
$WScript = New-Object -ComObject WScript.Shell
Get-ChildItem -Path "$env:USERPROFILE\Desktop\ClearIEData.lnk" |
ForEach-Object {
$WScript.CreateShortcut($_.FullName).TargetPath | Out-File -FilePath 'D:\Temp\LinkFileData.txt' -Append -WhatIf
}
Get-Content -Path 'D:\Temp\LinkFileData.txt'
<#
# Results
D:\Tools\ClearIEData.cmd
#>
There is a folder containing database backup files. I need to recursively check all folders and export the list of last backup files in each folder.
I have a code here that contains my idea. just I have to add this part:
-check for each selected file(selected file is the last created backup file) if the file creation time is older than 24 hours, export in csv file.
Thanks in advance
[Cmdletbinding()]
param(
[Parameter(Position=0,Mandatory=$false,ValueFromPipeline=$true)]$path=
"\F:\backups",
[Parameter(Position=1,Mandatory=$false,ValueFromPipeline=$true)]
$OutPutFilepath=
"f:\backup-daily.csv"
)
function Get-LastestWroteFile{
[Cmdletbinding()]
param(
[Parameter(Position=0,Mandatory=$true)]$Folder
)
begin{
$Latest = Get-ChildItem $Folder.FullName -File | select FullName,
CreationTime, LastAccessTime, LastWriteTime, Attributes, #{N='SizeInMb';E=
{$_.Length/1mb}},Name | Sort-Object CreationTime | select -Last 1
}
process{
}
end{
#new custom object with 3 props.
if($Latest){
return New-Object PSobject -Property #{"FullName"=$latest.Name;
LastWriteTime =
$latest.LastWriteTime;"Folder"=$folder.FullName;"SizeInMB" =
[math]::Round($Latest.SizeInMB,3)} #FileInfo=$Latest; }
}
}
}
$OutPut=#()
Get-ChildItem -Directory -Path $path -Recurse | foreach{
$OutPut+= Get-LastestWroteFile $_
}
$OutPut | ConvertTo-Csv -NoTypeInformation -delimiter '|' | Out-File -
FilePath $OutPutFilepath
an advanced function would not be required, try below
Get-ChildItem -Path $Path -Recurse -File | Where-Object -FilterScript {
([Datetime]::Now - $_.CreationTime ).Hours -gt 24
} | Select-Object -Property Name,LastWriteTime,FullName,#{N='SizeInMb';E=
{$_.Length/1mb}},
i have project assigned to me, first i need to find file in which directory it is in server, code i have written
$drive = get-psdrive |select root |select-string -pattern ':'
Write-Host $drive
foreach ($a in $drive)
{
Get-ChildItem $a -recurse -filter "*DBaEnvProd*" |select directory
}
there shd be one output a there will be only one dbenvprod on server
how to get one value
output iam getting
Get-ChildItem : Cannot find drive. A drive with name '#{Root=C' does not exist.
At D:\temp.ps1:6 char:26
+ Get-ChildItem <<<< $a -recurse -filter "*DBaEnvProd*" |select directory
Get-ChildItem : Cannot find drive. A drive with name '#{Root=D' does not exist.
At D:\temp.ps1:6 char:26
+ Get-ChildItem <<<< $a -recurse -filter "*DBaEnvProd*" |select directory
Get-ChildItem : Cannot find drive. A drive with name '#{Root=E' does not exist.
At D:\temp.ps1:6 char:26
+ Get-ChildItem <<<< $a -recurse -filter "*DBaEnvProd*" |select directory
Get-ChildItem : Cannot find drive. A drive with name '#{Root=F' does not exist.
At D:\temp.ps1:6 char:26
+ Get-ChildItem <<<< $a -recurse -filter "*DBaEnvProd*" |select directory
Get-ChildItem : Cannot find drive. A drive with name '#{Root=Z' does not exist.
At D:\temp.ps1:6 char:26
+ Get-ChildItem <<<< $a -recurse -filter "*DBaEnvProd*" |select directory
Add -InputObject parameter:
Select-String -InputObject {$_.Root} -Pattern ':'
Get-PSDrive | ForEach-Object {Get-ChildItem -LiteralPath $_.Root -Filter "*DBaEnvProd*" -Recurse}
I want to out put folder name, lastwritetime and folder size, how can i combine both of the results in to one line?
For folder name and lastwritetime:
get-item "\\server-01\Y$\Server1" | select name,lastwritetime
For folder size:
$folder = (Get-ChildItem "\\server-01\Y$\Server1" -recurse | Measure-Object -property length -sum)
$size = "{0:N2}" -f ($folder.sum / 1024MB) + " GB"
I need output format like this:
Name LastWriteTime Size
Server1 2014-05-05 55G
Also how to make a loop of running this function through a list of PCs?
Any idea please?
For Folder name and lastwritetime:
Get-Item $Path | Where-Object { $_.BaseName ,$_.LastWriteTime}
For folder size:
$log="C:\log.txt"
$Path = "C:\Test"
$Items = Get-ChildItem $Path | Where-Object {$_.PSIsContainer -eq $True} | Sort-Object
foreach ($f in $Items){
$itemSum = Get-ChildItem ("$Path\" + $f.Name) | Select-Object #{ l="Path" ; e = {$f}},LastWriteTime,#{l="Size" ; e={((Get-childitem -recurse | measure-object length -sum).Sum /1KB)}}
}
Enjoy!!
FYI
Query Folder tree for Size and export to a log on a server
Select-Object will be your friend here:
foreach ($c in (get-content .\Servers.txt))
{ Get-Childitem \\$c\y$\mydirectory | select-object #{l="Name" ; e = {$c}},Lastwritetime,#{l="Size" ; e={(Get-childitem -recurse | measure-object length -sum).sum}} }
But you could also do yourself a favor and add a function like get-foldersize to your profile or to a standard tools module.
http://gallery.technet.microsoft.com/Get-FolderSize-b3d317f5
Here's a true one-liner with some formatting.
Get-ChildItem -Directory -Force|ForEach {"{0,-30} {1,-30} {2:N2}MB" -f $_.Name, $_.LastWriteTime, ((Get-ChildItem $_ -Recurse|Measure-Object -Property Length -Sum -ErrorAction Stop).Sum/1MB)}
Result: