I have this script that I need to basically get all the .pdf files in a folder and then in that moment it needs to check if any of those file names are in a txt file containing filenames and if it is it will do some set of steps, same as if it is not. I have only made it so far as im not very fluent with powershell.Below is what i got if anyone can help me out! Thanks!
$dir = "C:\Users\user\Downloads\*.pdf"
$names = "C:\Users\user\Downloads\content.txt"
#check for .pdf files in folder
If (Test-Path -Path $dir )
{
$files = Get-ChildItem $dir
foreach($file in $files)
{
# Steps to search for filename within $names file that contains list of files
# Steps if file found
{
#do these steps
}
else
{
#do these steps instead and then add all the filenames to $names file
Add-Content $names $file.Name
}
}
}
Else
{
Write-Host "N/A"
Exit
}
CodePudding user response:
You can try using regular expressions for this:
$inNames = Select-String -Path "$names" -Pattern ('^' "$file" '$') -CaseSensitive -List
This returns the first line in "$names"
file consisting solely of "$file"
, case-sensitive.
CodePudding user response:
To rephrase wat you're asking for...
- Search for all PDFs in
"C:\Users\user\Downloads\"
. - Compare to the names found in
"C:\Users\user\Downloads\content.txt"
.- If they're already in the list, do "other stuff".
- If not, add the names to
"C:\Users\user\Downloads\content.txt"
?
Presuming my assumptions are correct, you can use the following:
$fileNames = Get-Content -Path ($path = 'C:\Users\user\Downloads\content.txt')
foreach ($file in (Get-ChildItem -Path ($path | Split-Path) -Filter '*.pdf' -File))
{
if ($file.BaseName -in $fileNames) {
Write-Verbose -Message ("File name ['{0}'] already in list" -f $file.Name) -Verbose
#The rest of the code here for the current iteration of the file found in 'content.txt'.
}
else {
Write-Verbose -Message ("Adding ['{0}'] to '{1}'" -f $file.Name,$path) -Verbose
Add-Content -Path $path -Value $file.BaseName -WhatIf
}
}
In the first if
statement, the file(s) are checked to see if they are already in the list. If the file names are already in the list, display a message saying so - then, in the same if
body, you can add the rest of the code for the files that were found.
In the else
statement, the file(s) not found will have the name added to the list.
Remove the -WhatIf
common/safety parameter from Add-Content
once you've dictated that is the appropriate action you want it to take, for the files that weren't found.