Get-ChildItem -Path in NLog file - powershell

If I have this:
Get-ChildItem -Path $BACKUP_REG_PATH >> $TOT_LOG_FILE
I will get a fine list in my log file like this:
Directory: C:\WS\BACKUP\xxxx-Reg
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 2016-05-17 11:04 494018 xxxxxx_REGISTRY_EVENTLOG__2016-05-17__11_04_38.reg
-a--- 2016-05-17 11:08 494018 xxxxxx_REGISTRY_EVENTLOG__2016-05-17__11_08_59.reg
-a--- 2016-05-17 11:10 494018 xxxxx_REGISTRY_EVENTLOG__2016-05-17__11_10_31.reg
I want to do this for NLog instead but I don't know how to get a nice list as above.
If I do this:
$regtxt=Get-ChildItem -Path $BACKUP_REG_PATH
$LOGGER.Trace("$regtxt");
I only get a long list on the same row with the Name column.
Any ideas how to solve this?

I don't know NLog but the Trace method probably output the trace in a single line. You could iterate over each item using the Foreach-Object cmdlet and write a trace:
Get-ChildItem -Path $BACKUP_REG_PATH | Foreach-Object {
$LOGGER.Trace($_);
}
Note: This will not output the name column, you may have to trace this yourself.
To solve this, you could pipe the output to the Out-String cmdlet which will give you a single string. You then have to split the string by [System.Environment]::NewLine to get an array to iterate over it:
((Get-ChildItem | select -first 4 | Out-String) -split [System.Environment]::NewLine) |
ForEach-Object {
$LOGGER.Trace($_);
}

Related

I want to import a csv to use as filter in the powershels gci command

I have a csv file with extension and description.
I want to import that file and use it as the filter parameter in a gci command.
But I get no results.
I expect to get a list of the jpg files but get no results.
$extensions=Import-CSV -Path c:\scripts\Media-extension-foto.csv
#$extensions=Import-CSV -Path c:\scripts\Media-extension-foto.csv -header extension
$extensions.extension
$src = "c:\scripts\"
#gci c:\scripts\ -Include $Extensions.extension #-Force -recurse
#gci c:\scripts\ -filter $Extensions.extension #-Force -recurse
gci c:\scripts\|where{$_ -like $extensions.extension}`
my csv file looks like this (just made a small file for testing)
extension,"description"
*.JPEG,JPEG Image
*.JPF,JPEG 2000 Image
*.JPG,JPEG Image
*.JPG_LARGE,Twitter Large JPEG Image
There are jpg files in that folder :
Directory: C:\Scripts
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 23/11/2022 11:02 509592 nieuw9754560_02-10.jpg
-a--- 23/11/2022 11:02 576486 nieuw9754560_02-15.jpg
-a--- 23/11/2022 11:02 641802 nieuw9754560_02-20.jpg
-a--- 23/11/2022 11:01 705702 nieuw9754560_02-25.jpg
-a--- 23/11/2022 11:01 763249 nieuw9754560_02-30.jpg
I've just tested this - I think all you're missing is changing the $_ to $_.Extension for the Get-ChildItem, on the last line.
Hope that helps.
Doesn't directly fix the code but here's another way of getting the result using foreach to iterate through each extension in the array:
foreach($e in $extensions.extension) {
gci c:\scripts\ | where {$_ -like $e}
}

Powershell: How To Extract Binary File Attributes From Directory Listing

In PowerShell, I can get a nice list of files in descending sorted order using a filter:
$tt = gci -Path \\Munis2\musys_read\export_test\* -Include "ARLMA_*.csv" | sort LastWriteTime -Descending
PS H:\WindowsPowerShell\Scripts\ProductionScripts\Munis> $tt
Directory: \\Munis2\musys_read\export_test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 03/04/2022 3:09 AM 25545520 ARLMA_20220304030027.csv
.
.
.
Then, I can get just the name of the file for the purposes of transferring that file to an FTP site.
PS H:\WindowsPowerShell\Scripts\ProductionScripts\Munis> $tt[0].Name
ARLMA_20220304030027.csv
How can I parse $tt[0].LastWriteTime
PS H:\WindowsPowerShell\Scripts\ProductionScripts\Munis> $tt[0].LastWriteTime
Friday, March 4, 2022 3:09:14 AM
into something that looks like yymmddhhmmss, or is there a way to get the binary time of the file the last time it was accessed?
The ToString() method can be used to format the date into a string. Are you sure that a two digit year is appropriate?
$DateResult = (Get-ChildItem -Path \\Munis2\musys_read\export_test\* -Include "ARLMA_*.csv" |
Sort-Object -Property LastWriteTime -Descending |
Select-Object -First 1).LastWriteTime.ToString('yyMMddHHmmss')

powershell iterate all users and display recent lnk files

Iterate all windows $users and display the recent .lnk files from a specific path!
I have tried importing this module - https://gist.github.com/picheljitsu/cc2ed99cbae7caad3abb0928cd8a286b
Get-RecentFiles and I want to iterate with $users after getting the users with get-localuser
$user = (Get-LocalUser | Select-Object Name) |
ForEach-Object { Get-RecentFiles $user }
should display recent files of all users recent directory..
Directory: C:\Users\admin\AppData\Roaming\Microsoft\Windows\Recent
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 6/30/2019 6:59 PM AutomaticDestinations
d----- 7/1/2019 3:21 PM CustomDestinations
Directory: C:\Users\user2\AppData\Roaming\Microsoft\Windows\Recent
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 6/30/2019 6:59 PM AutomaticDestinations
d----- 7/1/2019 3:21 PM CustomDestinations
The result of Get-LocalUser | Select-Object Name is an array of users. When you pass this array to the pipeline, it will "unwrap" its items and pass them one at a time, and this item will be declared as $_ variable.
Passing Arrays to Pipeline
If a function returns more than one value, PowerShell wraps them in an array. However, if you pass the results to another function inside a pipeline, the pipeline automatically "unwraps" the array and processes one array element at a time.
ExpandProperty parameter is used to convert the object property Name to string to be used in the Get-RecentFiles function.
Modify your code and try this:
Get-LocalUser | Select-Object -ExpandProperty Name | Foreach-Object {Get-RecentFiles $_}
Update
The above code will get some errors for the disabled users (e.g: administrator, guest). To solve this, you have to only get the enabled users as follows:
Get-LocalUser | Where-Object Enabled | Select-Object -ExpandProperty Name | Foreach-Object {Get-RecentFiles $_}

Why $ _ does not return the complete object

I'm a beginner in powershell, I've been using it for just a few weeks, I was thinking about $_ when I saw this:
Get-ChildItem should return the files on a directory
PS C:\Users\Edu-mat\Powershell> Get-ChildItem
Diretório: C:\Users\Edu-mat\Powershell
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 10/08/2018 13:38 7 Test0.txt
-a---- 10/08/2018 13:42 5 Test1.txt
-a---- 10/08/2018 13:42 7 Test2.txt
-a---- 10/08/2018 13:43 8 Test3.txt
$_ Means current object in the pipeline.
but when i did Get-ChildItem | %{write-host $_} the output was not as expected
PS C:\Users\Edu-mat\Powershell> Get-ChildItem | %{write-host $_}
Test0.txt
Test1.txt
Test2.txt
Test3.txt
WHY $_ is not returning the entire object, it just printing the name of the file ?
can someone please explain me.
$_ is returning the entire object, however Write-Host expects a string, and so the .ToString() method is called on the object. In the case of System.IO.FileInfo its ToString() is overridden to output the name of the file.
Try this and see for yourself:
Get-ChildItem | %{Write-Host $_.ToString()}
Get-ChildItem | %{Write-Host $_.GetType()}
Get-ChildItem | %{Write-Host $_.Mode}
Write-Host is for writing information out to the console, so objects are formatted as strings, similar to if you had done gci | % { "$_" } (except the latter writes to the output stream not directly to the host).
If you want to write directly to the console but the same formatting you would see if sent to the console implicitly, use Out-Host as recommended by mklement0:
Get-ChildItem | Out-Host
His comment in full:
I suggest using Out-Host directly; also, perhaps surprisingly,
Write-Host "$_" is not always the same as Write-Host $_, because the
latter results in .ToString() getting called, which defaults to a
culture-sensitive representation (where available), whereas
PowerShell's string interpolation by design always uses the invariant
culture

How to split string and rename files in PowerShell?

I want to bulk rename the files in my folder, and all of them have the format of FilenameYeara\b.pdf, for example, TestData2001a.pdf, File2015b.pdf. I want to rename all of them to something like [Yeara\b]Filename, such as [2001a]TestData. The problem is that I don't know how can I split my filename into two parts (actually three if we count the extension, .pdf part), such that I put that second part as the first part of the file name.
Get-ChildItem | Rename-Item {$_.name -replace ‘current’, ’old’ }
How can I achieve this?
This does the regex match "anything, four digits, one character, .pdf" and replaces it with those items in the new ordering.
PS D:\t> gci | ren -newname { $_ -replace '(.*)(\d{4})(.)\.pdf', '[$2$3]$1.pdf' }
Directory: D:\t
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 13/05/2016 02:54 0 File2015b.pdf
-a--- 13/05/2016 02:53 0 TestData2001a.pdf
becomes
Directory: D:\t
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 13/05/2016 02:53 0 [2001a]TestData.pdf
-a--- 13/05/2016 02:54 0 [2015b]File.pdf
(Maybe try it with -Whatif before running for real)
This should get you started
$Matches.Clear()
Get-Item | % {
$_.BaseName -match "(\D+)([0-9]{4}[ab])"
Rename-Item -Path $_.FullName -NewName "$($Matches[2])$($Matches[1])$($_.Extension)"
}