Powershell: Add a timestamp when the data was collected - powershell

i have this code
$result = get-childitem "e:\tms\valid_2" -recurse -file | select fullname,*time
echo $result
i want to add another column which will be the timestamp the data was collected like this and print it out as a CSV.
FullName CreationTime LastAccessTime LastWriteTime DatacollectionTime
Is this possible?
Thanks and regards!

Use a calculated property:
# Add the output of `Get-Date` to each object as a "DataCollectionTime" property
$result =
Get-ChildItem "e:\tms\valid_2" -Recurse -File |
Select-Object FullName,*Time,#{Name='DataCollectionTime';Expression={Get-Date}}
# Export to csv
$result |Export-Csv path\to\export.csv -NoTypeInformation
# Or if you just want a string
$result |ConvertTo-Csv -NoTypeInformation

Related

Powershell export result to txt with format

I have a small script that looks for the two files with the smallest size and exports them to a txt.
The problem is that the result is exported with a "bit weird format".
$checksize = gci -r| sort -descending -property length | select -last 2 name, length | Add-Content -Path C:\log.txt
And the result
#{Name=fileexample.txt; Length=3482342}
#{Name=server.iso; Length=548238474}
I would like only the names of the files and their size to appear.Does anyone know how I could do it?
Thanks.
Good Day
Try to use Out-File instead of Add-Content
#sample path to csv file
$CsvFile = Import-CSV -Path C:\data.csv -Delimiter ";" -Header File,Length
ForEach ($u in $CsvFile)
{
$A = ($u.File).Replace("#{Name=","")
$B = (($u.Length).Replace("Length=","")).Replace("}","")
Write-Host $A $B
}
or export to csv
gci -Path C:\test -r| sort -descending -property length | select -last
2 name, length|Export-Csv C:\log.csv -NoTypeInformation

powershell foreach shows duplicate result

I use powershell to automate extracting of selected data from a CSV file.
My $target_servers also contains two the same server name but it has different data in each rows.
Here is my code:
$target_servers = Get-Content -Path D:\Users\Tools\windows\target_prd_servers.txt
foreach($server in $target_servers) {
Import-Csv $path\Serverlist_Template.csv | Where-Object {$_.Hostname -Like $server} | Export-Csv -Path $path/windows_prd.csv -Append -NoTypeInformation
}
After executing the above code it extracts CSV data based on a TXT file, but my problem is some of the results are duplicated.
I am expecting around 28 results but it gave me around 49.
As commented, -Append is the culprit here and you should check if the newly added records are not already present in the output file:
# read the Hostname column of the target csv file as array to avoid duplicates
$existingHostsNames = #((Import-Csv -Path "$path/windows_prd.csv").Hostname)
$target_servers = Get-Content -Path D:\Users\Tools\windows\target_prd_servers.txt
foreach($server in $target_servers) {
Import-Csv "$path\Serverlist_Template.csv" |
Where-Object {($_.Hostname -eq $server) -and ($existingHostsNames -notcontains $_.HostName)} |
Export-Csv -Path "$path/windows_prd.csv" -Append -NoTypeInformation
}
You can convert your data to array of objects and then use select -Unique, like this:
$target_servers = Get-Content -Path D:\Users\Tools\windows\target_prd_servers.txt
$data = #()
foreach($server in $target_servers) {
$data += Import-Csv $path\Serverlist_Template.csv| Where-Object {$_.Hostname -Like $server}
}
$data | select -Unique | Export-Csv -Path $path/windows_prd.csv -Append -NoTypeInformation
It will work only if duplicated rows have same value in every column. If not, you can pass column names to select which are important for you. For ex.:
$data | select Hostname -Unique | Export-Csv -Path $path/windows_prd.csv -Append -NoTypeInformation
It will give you list of unique hostnames.

Scan the properties of files on an excel sheet by Powershell

I have a task that requires to scan the property of all the files indicated by certain directories where the files are stored. I need my code to read the following line of information separated by the delimiter "," stored in a .txt file as follows (the directory is made up by myself on my own device and I went ahead making up some blank .xlsx files to test my code:
Jakarta,C:\\temp\Hfolder,C:\temp\Lfolder
I currently have code that looks like this:
$LocContent = Import-Csv "C:\temp\Location.txt" # -Header $fileHeaders
ForEach($line in $LocContent){C:\temp\test1.csv -NoTypeInformation
#split fields into values
$line = $LocContent -split (",")
$country = $line[0]
$hDrivePath = $line[1]
$lDrivePath = $line[2]
Get-ChildItem $hDrivePath -force -include *.xlsx, *.accdb, *.accde, *.accdt, *.accdr -Recurse
Get-ChildItem $lDrivePath -force -include *.xlsx, *.accdb, *.accde, *.accdt, *.accdr -Recurse
? {
$_.LastWriteTime -gt (Get-Date).AddDays(-5)
}
Select-Object -Property Name, Directory, #{Name="Owner";Expression={(Get-ACL $_.Fullname).Owner}}, CreationTime, LastAccessTime, #{N="Location";E={$country}}, #{N='size in MB';E={$_.Length/1024kb}} | Export-Csv
}
However there is no output on the .csv file I assigned to output the information. What is wrong in my code?
Thanks!
There are several flaws within your code:
The Select has neither an -InputObject nor is anything piped to it so there can't be an output
You should decide whether you treat C:\temp\Location.txt as
a text file with Get-Contentand a split
or as a csv with headers
or without headers and supply them to the import.
The Get-ChildItem output isn't piped anywhere nor stored in a variable so it goes to the screen.
Export-Csv needs a file name to export to.
Try this untested script:
## Q:\Test\2018\06\26\SO_51038180.ps1
$fileHeaders = #('country','hDrivePath','lDrivePath')
$extensions = #('*.xlsx','*.accdb','*.accde','*.accdt','*.accdr')
$LocContent = Import-Csv "C:\temp\Location.txt" -Header $fileHeaders
$NewData = ForEach($Row in $LocContent){
Get-ChildItem $Row.hDrivePath,$Row.lDrivePath -Force -Include $extensions -Recurse |
Where-Object LastWriteTime -gt (Get-Date).AddDays(-5) |
Select-Object -Property Name,
Directory,
#{Name="Owner";Expression={(Get-ACL $_.Fullname).Owner}},
CreationTime,
LastAccessTime,
#{N="Location";E={$Row.country}},
#{N='size in MB';E={$_.Length/1024kb}}
}
# you choose what to do with the result uncomment the desired
$NewData | Format-Table -Auto
# $NewData | Out-Gridview
# $NewData | Export-Csv '.\NewData.csv' -NoTypeInformation

Export content of multiple files to a CSV

Im trying to export the content of multiple .log files into a single CSV.
I think I'm close, but I just can't figure out what I'm doing wrong. I'm guessing it's somewhere in the foreach:
$dir = "\\server\c$\folder1\folder2"
$filter = "*.log"
$files = Get-ChildItem -path $dir -filter $filter | Sort-Object LastAccessTime -Descending | Select-Object -First 10
foreach ($file in $files){
Get-Content $file | convertTo-csv | export-csv -path "\\server\share\test.csv"
}
I've tried to write the get-content line in so many ways, but none seem to work.
When I do $files.name, it lists up the files perfectly.
The error I get from the code is "Cannot find path 'C:\Users\Myname\filename1.log' because it does not exist.. I don't understand why, because I never spesified the c:\users path..
You can simply use the Import-CSV cmdlet to load the CSV instead of the Get-Content and convertTo-csv cmdlet:
$files = Get-ChildItem -path $dir -filter $filter |
Sort-Object LastAccessTime -Descending |
Select-Object -First 10 |
Select-Object -ExpandProperty FullName
Import-Csv -Path $files | Export-Csv "\\server\share\test.csv"
try:
get-content -path $file.Fullname

powershell why can't I export this object to csv

I'm trying to count the number of words per PDF file in a source folder and export the name and wordcount to a csv. But my output csv seems to count the number of PDFs (123) although the content of my object seems right.
Snippet
$source = 'C:\Data\SCRIPTS\R\TextMining\PDFs'
$results= #{}
Get-ChildItem -Path $source -Filter *.pdf -Recurse | ForEach-Object{
$count = Get-Content $_.FullName | Measure-Object -Word
$results.Add($_.FullName, $count.Words)}
$results
Export-Csv C:\Data\SCRIPTS\R\TextMining\PageClustering\PDFs\PGs\PGs_WC.csv -InputObject $results -notypeinformation
I can display the filename and wordcount to the console but the pipe to csv comes out with errors.
Output
IsReadOnly IsFixedSize IsSynchronized Keys Values SyncRoot Count
FALSE FALSE FALSE System.Collections.Hashtable+KeyCollection System.Collections.Hashtable+ValueCollection System.Object 123
I'm learning to use PS - what am I doing wrong?
Please try following:
$source = 'C:\Data\SCRIPTS\R\TextMining\PDFs'
$results= #()
Get-ChildItem -Path $source -Filter *.pdf -Recurse | ForEach-Object{
$count = Get-Content $_.FullName | Measure-Object -Word
$results += New-Object PSObject -Property #{
'Name' = $_.FullName
'Wert' = $count.Words
}
}
$results
$results | Export-Csv C:\Data\SCRIPTS\R\TextMining\PageClustering\PDFs\PGs\PGs_WC.csv -notype
Since $Results is a hashtable, you'll want to export the elements inside it, rather than the hashtable itself. In order to do so, you'll need to pipe the Values array to Export-Csv:
$results.Values |Export-Csv C:\Data\SCRIPTS\R\TextMining\PageClustering\PDFs\PGs\PGs_WC.csv -NoTypeInformation