Append same string to all variables in column of CSV in powershell - powershell

I would like help on how to add string -Config to each name in column Name.
CSV file contains:
FullName Name LastWriteTime
\\remotecomputer\ Henry 4/30/2020 3:44:57 PM
\\remotecompter\ Magy 12/7/2020 9:04:28 PM
The desired output:
FullName Name LastWriteTime
\\remotecomputer\ Henry-Config 4/30/2020 3:44:57 PM
\\remotecompter\ Magy-Config 12/7/2020 9:04:28 PM
My current code:
$InvoiceList = Import-CSV -Path C:\$source-PREP.csv | foreach($list in $InvoiceList){
$Name=$($list.name)
Get-ChildItem -Path 'C:\Names' -Filter *.txt | where {$_.Name -like '*' }|Copy-Item -Destination 'c:\newfolder' -Force }

Since your file has only a few known columns, you could use Select-Object and append -Config to the values in the Name column using a calculated property:
$data = Import-CSV -Path "C:\$source-PREP.csv" |
Select-Object FullName, #{Name = 'Name'; Expression = {'{0}-Config' -f $_.Name}}, LastWriteTime
$data | Export-Csv -Path "C:\$source-PREP.csv" -NoTypeInformation -Force
Result
FullName Name LastWriteTime
-------- ---- -------------
\\remotecomputer\ Henry-Config 4/30/2020 3:44:57
\\remotecompter\ Magy-Config 12/7/2020 9:04:28

You just need to iterate of each line in the CSV and update the name property. Once done export back out to CSV
$csvfile = 'some\path\to\file.csv'
$csvdata = Import-Csv $csvfile
$csvdata | ForEach-Object {$_.name = $_.name + '-Config'}
$csvdata | Export-Csv $csvfile -NoTypeInformation

Related

Get LastAccessTime for each subfolders in a csv folder list

I have a csv ($HomeDir) file like this:
Users,Comments,HomeDir
user1,account1,c:\folder1
user2,account2,c:\folder2
user3,account3,c:\folder3
I get succesfully LastAccessTime for each subfolder in 'HomeDir' column with this code:
$csv = Import-Csv $HomeDir
foreach ($folder in $csv.HomeDir) {
Get-ChildItem $folder -ErrorAction SilentlyContinue |
? {$_.PSIsContainer -eq "True"} |
Select-Object FullName, #{Name='LastAccessTime'; Expression={$_.LastAccessTime.ToString('yyyyMMdd')}} |
Sort-Object -Descending -Property LastAccessTime |
Export-Csv $newcsv -NoTypeInformation -Append
}
The result of $newcsv is:
"FullName","LastAccessTime"
"c:\folder1\Sub1","20201223"
"c:\folder1\Sub1a","20201223"
"c:\folder1\Sub1b","20201223"
"c:\folder2\Sub2","20201218"
"c:\folder2\Sub2a","20201218"
"c:\folder3\Sub3","20201212"
"c:\folder3\Sub3a","20201215"
"c:\folder3\Sub3b","20181215"
"c:\folder3\Sub3c","20201011"
The questions is: is there a way to assign the related User based on corresponding 'Users' column?
It would also be enough for me to get an output like this
"Users","FullName","LastAccessTime"
"user1","c:\felder1\Sub1","20201223"
"user1","c:\folder1\Sub1a","20201223"
"user1","c:\folder1\Sub1b","20201223"
"user2","c:\folder2\Sub2","20201218"
"user2","c:\folder2\Sub2a","20201218"
"user3","c:\folder3\Sub3","20201212"
"user3","c:\folder3\Sub3a","20201215"
"user3","c:\folder3\Sub3b","20181215"
"user3","c:\folder3\Sub3c","20201011"
Thanks in advance
Instead of pulling the HomeDir property out before the loop, just reference it inside the loop and add the Users property to your Fullname and LastAccessTime properties.
$properties = #{Name='User'; Expression={$user}},
'FullName',
#{Name='LastAccessTime'; Expression={$_.LastAccessTime.ToString('yyyyMMdd')}}
Import-Csv $HomeDir | ForEach-Object {
$user = $_.users
Get-ChildItem $_.HomeDir -ErrorAction SilentlyContinue |
Where-Object {$_.PSIsContainer -eq "True"} |
Select-Object $properties |
Sort-Object -Descending -Property LastAccessTime
} | Export-Csv $newcsv -NoTypeInformation
To make it easier to read I put the properties in a variable beforehand. Also, if you are on powershell version 3 or higher you can use -Directory parameter in lieu of $_.PSIsContainer -eq $true. Finally, if you use the Foreach-Object instead of a foreach loop you can pipe to export and not have to use -Append opening and closing the file several times.
$properties = #{Name='User'; Expression={$user}},
'FullName',
#{Name='LastAccessTime'; Expression={$_.LastAccessTime.ToString('yyyyMMdd')}}
Import-Csv $HomeDir | ForEach-Object {
$user = $_.users
Get-ChildItem $_.HomeDir -Directory -ErrorAction SilentlyContinue |
Select-Object $properties | Sort-Object -Descending -Property LastAccessTime
} | Export-Csv $newcsv -NoTypeInformation
I propose my version.
$HomeDir="c:\temp\input.csv"
$newcsv="c:\temp\output.csv"
Import-Csv $HomeDir | %{
#save user name
$User=$_.Users
Get-ChildItem $_.HomeDir -ErrorAction SilentlyContinue -Directory |
Sort LastAccessTime -Descending |
select #{N='Users'; E={$User}}, FullName, #{N='LastAccessTime'; E={$_.LastAccessTime.ToString('yyyyMMdd')}}
} | Export-Csv $newcsv -NoType

Powershell: Add a timestamp when the data was collected

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

Column Directory empty?

I thought that applying this answer about replacing a path would work for:
$folder = 'C:\test'
$List = Get-ChildItem $folder -Recurse | Sort-Object -Property LastWriteTime
$List | Format-Table name, LastWriteTime, #{Label="Directory"; Expression={$_.Directory.Replace($folder, "")}}
Instead I get nothing in Directory column whereas I should get
\subfolder\
since the files are in
c:\test\subfolder
Name LastWriteTime Directory
---- ------------- ---------
test.1.png 7/21/2018 10:20:44 PM
test.2.png 7/21/2018 10:21:16 PM
test.3.png 7/21/2018 10:21:43 PM
subfolder 9/10/2018 6:53:28 PM
The Directory member of Get-ChildItem is a System.IO.DirectoryInfo. It has a member, Name, that can be used.
PS H:\clan\2018-09-05> (Get-ChildItem).Directory | Get-Member
TypeName: System.IO.DirectoryInfo
Try using:
Get-ChildItem | ForEach-Object { $_.Directory.Name }

How to look for a string within the contents of each file on a list? -Powershell

I have the following line which gives me a list of files.
{Get-ChildItem -Recurse -Force $filePath | sort-object -property CreationTime -descending | where { $_.CreationTime.dayofyear -eq $today } | Where-Object { ($_.PSIsContainer -eq $false) -and ( $_.Name -like "*FILE1*" -or $_.Name -like "*FILE2*" -or $_.Name -like "*FILE3*") } | Select-Object Name,CreationTime,CreationDay | Format-Table -AutoSize * }
Here's my results:
Name CreationTime
FILE1.022291 8/25/2016 8:25:07 AM
FILE2.022285 8/25/2016 2:25:10 AM
FILE3.022281 8/25/2016 2:25:08 AM
I'd like to look for two specific strings within each file of the results, and if any of the specific strings are found, display the whole line that the string is on below each result.
Here's what I'm hoping it can look like
Name CreationTime
FILE1.022291 8/25/2016 8:25:07 AM
THIS_IS_ALL_OF_LINE_4_WITH_SPECIFICSTRING1
FILE2.022285 8/25/2016 2:25:10 AM
THIS_IS_ALL_OF_LINE_16_WITH_SPECIFICSTRING2
FILE3.022281 8/25/2016 2:25:08 AM
THIS_IS_ALL_OF_LINE_7_WITH_SPECIFICSTRING1
Any help would be greatly appreciated. I'm somewhat new to Powershell so I'll do my best to help with any questions.
You can use Select-String for that info. Just get the file objects filter for the date you are looking for, then use Select-String. Select-String's out is FileName:LineNumber:Match.
PS> gci -File -Path $filePath file* | ? creationtime -gt (get-date).AddMinutes(-30) | Select-String -Pattern "SpecificString1|SpecificString2"
FILE1.022291:2:SpecificString1
FILE2.022285:4:SpecificString2
FILE3.022281:1:SpecificString1
And here is some formatting using named expressions in the select statement.
PS> gci -File -Path $filePath file* | ? creationtime -gt (get-date).AddMinutes(-30) | Select #{n='StringFound';e={$_ | Select-String -Pattern "SpecificString1|SpecificString2"}}, CreationTime;
StringFound CreationTime
----------- ------------
C:\temp\FILE1.022291:2:SpecificString1 8/25/2016 1:09:50 PM
C:\temp\FILE2.022285:4:SpecificString2 8/25/2016 1:09:50 PM
C:\temp\FILE3.022281:1:SpecificString1 8/25/2016 1:09:50 PM
Here is working with the select-string output:
PS> gci -File -Path $filePath file* | ? creationtime -gt (get-date).AddMinutes(-600) | Select-String -Pattern "Speci
ficString1|SpecificString2" -AllMatches | select LineNumber, FileName, Line, matches
LineNumber Filename Line Matches
---------- -------- ---- -------
2 FILE1.022291 SpecificString1 {SpecificString1}
4 FILE1.022291 sfdgdsgsdf SpecificString2 {SpecificString2}
6 FILE1.022291 SpecificString2 {SpecificString2}
4 FILE2.022285 SpecificString2 {SpecificString2}
1 FILE3.022281 SpecificString1 {SpecificString1}
Stringing two select string for a simple negate.
PS> gc C:\tmp\test.txt
this is foo
this is foo*bag
this is the bang
PS> gc C:\tmp\test.txt | Select-String -Pattern 'foo' -AllMatches | Select-String -SimpleMatch '*' -NotMatch -AllMatches | fl
IgnoreCase : True
LineNumber : 1
Line : this is foo
Filename : InputStream
Path : InputStream
Pattern : foo
Context :
Matches : {foo}

powershell script statement to fetch a particular file path

I have the following statement in PowerShell script that fetches a particular file
$imptext = "E:\imp\old"
$strAttachment = dir $imptext | sort -prop LastWriteTime | Where-Object {$_.name -like "*Imptextfiles*"} | Where-Object {$_.lastwritetime -gt (Get-Date).AddHours(-1)} | select -last 1 | foreach-object -process { $_.FullName }
How can I write to host the path of that file $strAttachment along with the exact file name?
You want to get the directory of the file? Just use the Split-Path cmdlet:
$attachmentDirectory = Split-Path $strAttachment
You could also use Get-DirectoryName:
$attachmentDirectory =[System.IO.Path]::GetDirectoryName($strAttachment)
Also, you can improve your inital script (using -Filter instead of two Where-Object)
$strAttachment = Get-ChildItem $imptext -Filter '*Imptextfiles*' |
Where-Object Lastwritetime -gt (Get-Date).AddHours(-1) |
sort LastWriteTime |
select -last 1 |
select -ExpandProperty FullName