Count the excel rows using the folder path - powershell

I have one folder named customer , under that there are multiple folders based on each customer name and under each customer I have excel of sheets which contain information in row wise.
I would like to extract this file structure into excel containing file path and number of rows contained in each of the excel.
I could able to list file names using below procedure.
Press Win-E to open Windows Explorer and locate the folder for which you need a file list.
Hold the Shift key, right-click the folder and select Open Command Window Here. This only works with folders, not libraries.
Libraries point to a specific folder, so select the folder located
under the library icon. If the library points to a drive, right-click
the drive letter from the folder tree.
Type dir /b > dirlist.txt without quotes and press Enter. This creates a list containing file names only. To include file sizes and
dates, type dir > dirlist.txt instead. To also include files in
sub-directories, type dir /b /s > dirlist.txt to create a list of
files with the full directory structure name, such as
C:\folder\subdirectory\file.txt.
Open Microsoft Excel and press Ctrl-O to bring up the Open dialog window.
Navigate into the folder containing the files. Click the file type drop-down menu and select Text Files (.prn,.txt,*.cvs).
Double-click dirlist.txt to open it.
Click Finish in the Text Import Wizard window to use the default options and import the directory list into Excel.
Please help in counting the rows also.

Your question is ambigous. I removed unnecessary/wrong tags.
Excel files can have more than one sheet, so you have to iterate/recurse the files from given startfolder and also all sheets in the workbook. Output is a table with the asked properties. Should be easy to save as a csv.
$BaseFolder = "X:\Path\to\Customers"
$xlCellTypeLastCell = 11
$AllSheets = New-Object System.Collections.Generic.List[object]
$Excel = New-Object -com excel.application
$Excel.DisplayAlerts = "False"
$XLfiles = Get-ChildItem -Path $BaseFolder -Filter *.xls* -File -Recurse
ForEach ($XLfile in $XLfiles) {
$WorkBook = $Excel.workbooks.open($XLfile.FullName)
for ($i = 1; $i -le $WorkBook.sheets.count; $i++){
$Sheet = $WorkBook.Sheets.Item($i)
$LastRow = $Sheet.UsedRange.SpecialCells($xlCellTypeLastCell).Row
$Obj = [pscustomobject][ordered]#{
ExcelFPath= $XLfile.FullName
Customer = ($XLfile.Directory).Name
ExcelFile = $XLfile.Name
SheetNo = $i
RowCount = $LastRow
}
$AllSheets.add($obj)
}
$Excel.Workbooks.Close()
}
$AllSheets | Format-Table -auto
## $AllSheets | Out-Gridview

Related

Renaming folders using [powershell] where the current name is partially matched to a csv list

Thanks in advance, i am totally new to PowerShell but i know it can rename files etc. so i'm hoping with your help it can be done with minimal fuss... I have been asked to rename circa 200 folders by adding in a 2nd reference to the folder name.
The current folder name example "11111_a1" and I want to rename it "11111_a1 12345678". I have created a CSV file with two columns, the first column has a partial match to the existing folder name being "20519" the second column has the additional reference that needs to be added "30534400"
The list is located in a Temp folder "C:\temp\FolderNameList.csv"
The target folders are located "O:\folder1\folder 2\0 - Sites"
I haven't tried anything yet but my searches have not been successful.
$BaseFolder = 'O:\folder\whatever'
# An array, one item for each data row in your CSV
$Rows = Import-Csv 'C:\temp\FolderNameList.csv'
foreach ($Row in $Rows)
{
$Name = $Row.Col1
# replace 'Col1' with whatever the column header is
$Path = Join-Path $BaseFolder $Name
$Suffix = $Row.Col2 # or whatever
$NewName = "$Name $Suffix"
Rename-Item $Path $NewName
}
That should fix you.
However, before you run the script on a lot of files, change foreach ($Row in $Rows) to foreach ($Row in $Rows[0]). Then it will only operate on the first file. Check it does what you expect!
If it works, take the [0] back out (and delete the first row of the CSV if you don't want error text, since that first row has now been done).

Get localized file (resource) names, as shown in Windows Explorer

I am looking for a PowerShell function like Get-LocalizedName($FilePath), returning the localized name of a file or its filename if it is not localized. I know that the localized names are stored in the LocalizedFileNames section of the respective desktop.ini files, but usually as resource file pointers rather than clear names.
Example: For the Administrative Tools folder and the locale de-DE, I want the clear name Windows-Verwaltungsprogramme instead of #%SystemRoot%\system32\shell32.dll,-21762.
I was not able to find such a function, and also was not successful in analyzing the attributes of Get-ChildItem or google a regarding solution.
Is there any such function that I could use from PowerShell (v7)?
The following solution works for folders only. See this answer for a solution that works for files, localized via LocalizedFileNames section of Desktop.ini.
This can be done using the Shell.Application COM object:
$shell = New-Object -ComObject Shell.Application
# Get full path to the admin tools folder
$adminToolsPath = [Environment]::GetFolderPath('AdminTools')
# Get the shell folder corresponding to this path
if( $folder = $shell.NameSpace( $adminToolsPath ) ) {
$folder.Title # Output localized title
}
# Alternative:
if( $folder = $shell.NameSpace( [Environment+SpecialFolder]::AdminTools ) ) {
$folder.Title # Output localized title
}
[Environment]::GetFolderPath() gives us the filesystem path of a system folder.
The Shell.Namespace() function returns a Folder object corresponding to this path which can be queried for its localized name.
The alternative shows how you can get the localized name more directly, by passing an enumeration value of [Environment+SpecialFolder] to the Shell.Namespace() function.
When passing a path to the Shell.Namespace() method, it works for any folder customized via "desktop.ini", even if it's not a system folder.
I finally found a solution for Get-LocalizedName, digging into 20 years old VBS code using GetDetailsOf:
function Get-LocalizedName {
Param([Parameter(Mandatory=$True)][string]$FilePath)
$ChildObj = Get-ChildItem $FilePath
$FldrName = $ChildObj.DirectoryName
$FileName = $ChildObj.Name
$Shell = New-Object -ComObject Shell.Application
$Folder = $Shell.Namespace($FldrName)
$File = $Folder.ParseName($FileName)
return $($Folder.GetDetailsOf($File,0))
}

Printing all Excel files in a folder using PowerShell

I have a PowerShell script that I wrote a few years ago and it worked great...until it didn't.
$shell = New-Object -com Shell.Application
$filepath = 'C:\Billing\Clients'
$shell.Namespace($filepath).Items() |
% { $_.InvokeVerb('Print') }
In the C:\Billing\Clients folder I copy ~100 Excel files. Each of these Excel files need to be printed, in the alphabetical order of the file name.
This was working great until this month. I guess an update to Excel changed things.
Now the script tries to open and print all of the Excel files at the same time. Previously it printed the files in serial.
This was awesome. Now it brings my system to it's knees and documents are printed in a random order.
Any ideas on how I can invoke the Print operation and wait for it to complete prior to calling the Print operation on the next file?
I have used this in the past to pull files into excel and print them. You will need to ensure your default print settings are set first or use $xl.ActivePrinter = "PRINTERNAME AS EXCEL SEES IT" to set it first.
#Open Excel
$xl = new-object -comobject excel.application
#don't show the window
$xl.visible = $false
#get all of your files
get-childitem "C:\SOME\Path" "*.xlsx" | foreach-object {
#open file
$wb = $xl.Workbooks.Open($_.FullName)
#print with defaults
$wb.PrintOut()
#close without saving any changes
$wb.Close($false)
}
#all done so close excel
$xl.Quit()

Powershell script to move files based on a source list (.txt

I have thousands of files in a directory (.pdf, .xls, .doc) and they all have a similar naming convention (the "type" is always a constant string, ie: billing or invoice);
accountname_accountnumber_type.pdf
accountname_ accountnumber_type.doc
accountname_accountnumber_type.xls
The task at hand is to receive a random list of accountnames and account numbers (the "type" is always a constant, ie: billing, invoice, shipping or order and they vary in format) and move them from Directory A into Directory B. I can get the list into a .csv file to match the accountname_accountnumber_type.
I have been trying to create a powershell script to reference the accountname_accountnumber and move those items from one directory A to directory B with no luck.
SAMPLE I found something a bit simpler, but I wanted to be able to edit this to create a new destination and not halt if the file is not found from this list. Also, if I could have this pick from a .txt list I think that would be easier than pasting everything.
$src_dir = "C:\DirA\"
$dst_dir = "D:\DirB-mm-dd-yyyy\" #This code requires the destination dir to already be there and I need to have the code output a new Directory, it could output based on date script run that would be amazing
$file_list = "accountname1_accountnumber001_type", #If I can select to import csv here
"accountname2_accountnumber002_type",
"accountname3_accountnumber003_type",
"accountname4_accountnumber004_type",
"accountname5_accountnumber005_type",
"accountname6_accountnumber006_type"
foreach ($file in $file_list) #This errors out and stops the script if the file is not located in source and I need to have the script continue and move on, with hopefully an error output
{
move-Item $src_dir$file $dst_dir
}
They can be any file format, I am trying to get the code to match ONLY the accountname and accountnumber since those two will define the exact customer. Whether it is invoice, billing or shipping doesn't matter since they want all files associated with that customer moved.
For Example there could be 4 of each for every account and the type format may vary from pdf, doc and xls, I need to move all files based on their first two indicators (accountname,accountnumber).
alice_001_invoice.pdf
alice_001_billing.doc
alice_001_shipping.pdf
alice_001_order.xls
George_245_invoice.pdf
George_245_billing.doc
George_245_shipping.pdf
George_245_order.xls
Bob_876_invoice.pdf
Bob_876_billing.doc
Bob_876_shipping.pdf
Bob_876_order.xls
Horman_482_invoice.pdf
Horman_482_billing.doc
Horman_482_shipping.pdf
Horman_482_order.xls
CSV:
accountname,accountnumber
Alice,001
George,245
Bob,876
Horman,482
How about this :
$CurrentDate = [DateTime]::Now.ToString("MM-dd-yyyy")
$DestinationDir = "D:\DirB-$CurrentDate"
New-Item $DestinationDir -ItemType Directory -ErrorAction SilentlyContinue
$AccountToMove = Import-CSV $CSVPath
Foreach ( $Account In $AccountToMove ){
$FilePattern = "*$($Account.AccountName)*$($Account.AccountNumber)*"
ls $SourceDir | Where Name -like $FilePattern | Move-Item -Destination $DestinationDir
}
The code part - you already edited off from the post - about moving files to subdirectories doesn't make much sense with your business rules. As you never show the sample CSV file contents, it's all guessing.
For easier processing, assume you got the following source files. Edit your post to show the CSV file contents and where you would like to move the files.
C:\some\path\A\Alice_001_bill.doc
C:\some\path\A\Alice_001_invoice.xls
C:\some\path\A\Bob_002_invoice.pdf
C:\some\path\A\Bob_002_invoice.doc
C:\some\path\A\Eve_003_bill.xls
C:\some\path\A\Eve_003_invoice.doc

Check for filenames in BlobStorage that starts with a string in Powershell

I am currently working with Powershell scripts to manage BlobStorage content in Windows-Azure. I want a script that reads content of a text file and displays names of files in BlobStorage that starts with this content. Im looking for a wildcard search that lists the names in BlobStorage which starts with the content specified in the textfile.
I have thought of a loop that searches through every line in the textfile and looks for names of files in BlobStorage that starts with the specified content in the textfile.
*If we have for example 2 rows in the textfile:*
43345-sdfssd-42342-sdfsf
32423-asdsad-23424-dghfs
And the filenames in BlobStorage are:
43345-sdfssd-42342-sdfsf-250.PNG
43345-sdfssd-42342-sdfsf-650.PNG
92323-asadad-12342-sdfds-1600.PNG
I want to compare the ID in the textfile with name of BlobStorage files, and show the full filenames of all files in BlobStorage containing this ID.
To specify this further here is what i was assuming:
foreach (ID in textfile)
{
files = find files in BlobStorage with name that starts with ID (ListBlobsWithPrefix?)
foreach (textfile in files)
{
Write filename to console
}
}
So far i have managed to make a connection to my blobstorage and it works, i can list names of Blobs in the images container. I have checked that everything works with reading the textfile aswell and printing content to console. What i have not managed to do is comparing the textfile ID with the filename of the Blob in BlobStorage and print the results in BlobStorage that starts with the ID. I have tried alot of solutions without any luck.
So far i have came up with this code:
#Make a connection to my BlobStorage
$SAN = "XX"
$SAK="X"
$creds = New-Object Microsoft.WindowsAzure.StorageCredentialsAccountAndKey($SAN, $SAK)
$client = New-Object Microsoft.WindowsAzure.StorageClient.CloudBlobClient("https://$SAN.blob.core.windows.net",$creds)
$bro = New-Object Microsoft.WindowsAzure.StorageClient.BlobRequestOptions
$bro.UseFlatBlobListing = $true
#Add $images blobcontainer and use flatbloblisting to list blobnames
$imagecontainer = $client.GetBlobDirectoryReference("images")
$images = $imagecontainer.ListBlobs($bro)
#Add textfile and assign it to a variable
$InputFile = Get-Content C:\transcript\hej.txt
#Loop to find everything in the input file and compare it to matching filenames in blobstorage. Return filenames that starts with the ID/contains the ID in the inputfile.
foreach ($ID in Get-Content $InputFile) {
Appreciate further help/solution.
Disclaimer: I have no experience with Azure, but a quick look at MSDN docs leads me to believe this would work:
foreach ($ID in $InputFile)
{
$image_matches = $images | Where-Object {$_.Name -match '^$ID'}
# process matching images here
}