Powershell script to list files without folder names - powershell

I open a PS in a folder then use
dir -name > asd.xls -recurse.
How can I modify this so it doesn't incude folders in the filenames?

Instead of using -name, try using
(Get-ChildItem -Recurse).Name > asd.xls
and be aware that you won’t get a valid Excel workbook that way. You can get a valid CSV that can be loaded into Excel with
(Get-ChildItem -Recurse) | Select-Object -Property Name | Export-CSV -Path asd.csv -NoTypeInformation

Related

Powershell List Excel Files and Copy

I apologize for the naivety of this post, please forgive my newness.
I have approximately 20,000 network files to filter through and copy certain ones to a local drive.
File List Requirements:
Excel files of various type (.xls, .xlsx, .xlsm)
Only files modified after 4/1/2022
Only files that contain "2022" in the filename
If the file meets those requirements then:
Copy the file to a local folder (original folder path structure doesn't matter, all files can go in one folder)
Output the original path and filename to a txt file, along with the lastwritedate
I have created the following code, which successfully obtains all excel files and creates the filename list
Get-ChildItem "D:\network_folder\" -Filter *.xls -Recurse | Select-Object -Property FullName, LastWriteTime |
Export-Csv -Path "C:\local_folder\file_list.csv" -Force -NoTypeInformation
However I cannot figure out the following issues:
how and where to filter for the lastwritetime
how and where to filter for the "2022" in the name
how and where to copy the files to the local folder
right now I'm just putting this all in the command line, do I need to make some file to run this process?
Thank you for any assistance you can provide!
I guess you want something like this.
It searches for files in the source folder with 2022 in the name and having .xls (or anything following xls) as extension.
It then loops over these items, creates the subfolder structure where they were found in the destination folder, copies the files and finally writes out a CSV file with information of the original file.
$sourcePath = 'D:\network_folder'
$destination = 'D:\dest_folder'
$refDate = [datetime]::new(2022,4,2) # --> next day date as of midnight
Get-ChildItem -Path $sourcePath -Filter '*2022*.xls*' -File -Recurse |
Where-Object {$_.LastWriteTime -ge $refDate} | ForEach-Object {
# create the destination folder if it does not already exist
$target = Join-Path -Path $destination -ChildPath $_.DirectoryName.Substring($sourcePath.Length)
$null = New-Item -Path $target -ItemType Directory -Force
# copy the file
$_ | Copy-Item -Destination $target
# output the wanted properties from the original file
$_ | Select-Object Name, FullName, LastWriteTime
} | Export-Csv -Path "C:\local_folder\file_list.csv" -Force -NoTypeInformation

Copying files to specific folder declared in a CSV file using Powershell Script

i am quite new to powershell and i am trying to make a script that copy files to certain folders that are declared in a CSV file. But till now i am getting errors from everywhere and can't find nothing to resolve this issue.
I have this folders and .txt files created in the same folder as the script.
Till now i could only do this:
$files = Import-Csv .\files.csv
$files
foreach ($file in $files) {
$name = $file.name
$final = $file.destination
Copy-Item $name -Destination $final
}
This is my CSV
name;destination
file1.txt;folderX
file2.txt;folderY
file3.txt;folderZ
As the comments indicate, if you are not using default system delimiters, you should make sure to specify them.
I also recommend typically to use quotes for your csv to ensure no problems with accidentally including an entry that includes the delimiter in the name.
#"
"taco1.txt";"C:\temp\taco2;.txt"
"# | ConvertFrom-CSV -Delimiter ';' -Header #('file','destination')
will output
file destination
---- -----------
taco1.txt C:\temp\taco2;.txt
The quotes make sure the values are correctly interpreted. And yes... you can name a file foobar;test..txt. Never underestimate what users might do. 😁
If you take the command Get-ChildItem | Select-Object BaseName,Directory | ConvertTo-CSV -NoTypeInformation and review the output, you should see it quoted like this.
Sourcing Your File List
One last tip. Most of the time I've come across a CSV for file input lists a CSV hasn't been needed. Consider looking at grabbing the files you in your script itself.
For example, if you have a folder and need to filter the list down, you can do this on the fly very easily in PowerShell by using Get-ChildItem.
For example:
$Directory = 'C:\temp'
$Destination = $ENV:TEMP
Get-ChildItem -Path $Directory -Filter *.txt -Recurse | Copy-Item -Destination $Destination
If you need to have more granular matching control, consider using the Where-Object cmdlet and doing something like this:
Get-ChildItem -Path $Directory -Filter *.txt -Recurse | Where-Object Name -match '(taco)|(burrito)' | Copy-Item -Destination $Destination
Often you'll find that you can easily use this type of filtering to keep CSV and input files out of the solution.
example
Using techniques like this, you might be able to get files from 2 directories, filter the match, and copy all in a short statement like this:
Get-ChildItem -Path 'C:\temp' -Filter '*.xlsx' -Recurse | Where-Object Name -match 'taco' | Copy-Item -Destination $ENV:TEMP -Verbose
Hope that gives you some other ideas! Welcome to Stack Overflow. πŸ‘‹

Exclude extension from an output file in PS?

My goal is to display items in the directory C:\test in a log file called log.txt without displaying the file-extensions of the files found, e.g. .zip, .pdf, etc.
My script so far:
Get-ChildItem -Path C:\Test\ -name |Out-File C:\test2\log.txt
How do I get the .log file to NOT display the extensions of the files found in the C:\test folder?
Use BaseName property instead of Name:
Get-ChildItem -Path C:\Test\ | Select-Object -ExpandProperty BaseName | Out-File C:\test2\log.txt
As there's no built-in -BaseName property for Get-ChildItem cmdlet, you need to get that property using Select-Object. Expanding the property allows you to get only the value of chosen property, without the header.
Another way to get BaseName value would be to use .BaseName like this:
(Get-ChildItem -Path C:\Test\).BaseName | Out-File C:\test2\log.txt
That form is shorter, but personally I prefer the first one due to readability and no need to remember about surrounding braces ().
Best practice
If you want to inspect what are the possible properties (and their values) of the object you have, you can also use Select-Object for that:
# Warning: HUGE OUTPUT POSSIBLE
Get-ChildItem -Path C:\test\| Select-Object *
# It's usually good to take only one object from the array
$obj = (Get-ChildItem -Path C:\test\)[0]
$obj | Select-Object *

Get Directories Names Only

I have a directoy X that has say 500 subdirectories. What I need is a quick way to just get only my directory and the names of these 500 subdirectories in my X directory (so, no Mode, no LastWriteTime or anything else, just the name) and pipe it to a file.
So, for example, I have this:
-X
|+Dir1
|+Dir2
|+Dir3
|
...
|+Dir500
What I want to get piped to a txt file is this
X/Dir1
X/Dir2
X/Dir3
...
X/Dir500
How can I do this using PowerShell or CommandLine?
I am using Windows 7 and PowerShell 4.0
Thanks,
Get-ChildItem will do the same thing as dir in command-line: it gets whatever is in your directory. You're looking only for directories. PS v3 and up has this built-in by using the flag of -directory. In older PowerShell versions, you can pipe your Get-ChildItem to a Where{$_.PSIsContainer to get directories and then pipe that to select Name to just get the names of the directories, not their full paths (e.g. "Dir1" vs. "X:\Dir1"). If you want the full path, use select FullName. Assuming you want that as a CSV, pipe that to Export-Csv followed by the name of the CSV you're creating, such as DirectoriesInX.csv and if you don't want the type information, add the flag of -NoTypeInformation.
PowerShell v3 and up:
Get-ChildItem "X:\" -directory | Select FullName | Export-Csv "DirectoriesInX.csv" -NoTypeInformation
PowerShell v2 and below:
Get-ChildItem "X:\" | Where{$_.PSIsContainer} | Select FullName | Export-Csv "DirectoriesInX.csv" -NoTypeInformation
I would have not used -Recurse based on requirement.
Moreover, OP wants to pipe output to a file :
(Get-ChildItem "X" -Directory).FullName | Out-File c:\myList.txt
The -Directory switch is only available from PS3.
The -Recurse switch would go as deep as possible in the tree and list all folders

The specified network name is no longer available in powershell

I have list of share path in a text file. I try to read the files and folders in each path and exporting to csv file using powershell script. I got some csv files with 0 KB.
so i try to test the existance of such network path using Test-Path command. few path shows it is exist but when itry to list out the directories of existing path using Dir \sharepath name i got error like "The specified network name is no longer available" Why??
Sharing code below..
foreach ($dir in (Get-Content $infile)) {
$outfilecsv='jerin-Download'+'.csv'
Get-ChildItem -Path $dir -Filter *.* -Recurse | Select-Object
Name,#{Name="Owner";Expression={(Get-ACL $_.fullname).Owner}},CreationTime,#{Name="FileModifiedDate";Expression={$_.LastWriteTime}},
#{Name="FileAccessedDate";Expression={$_.LastAccessTime}},#{Name="Attributes";Expression=
{$_.Attributes}},#{l='ParentPath';e={Split-Path $_.FullName}},
#{Name="DormantFor(days)";Expression={[int]((Get-Date)-$_.LastWriteTime).TotalDays}},
#{N="FileCategory";E={Get-FileSizeCategory($_)}},
#{Name="Size";Expression={if($_.PSIsContainer -eq $True){(New-Object -com
Scripting.FileSystemObject).GetFolder( $_.FullName).Size} else {$_.Length}}}|
Export-Csv -Path $outfilecsv -Encoding ascii -NoTypeInformation
}
Can anyone suggest
Thanks
Jerin