如何将文件名添加到文件中并在powershell中搜索



我有这个脚本,我需要它基本上把所有的.pdf文件都放在一个文件夹中,然后在那一刻,它需要检查这些文件名是否在一个包含文件名的txt文件中,如果是,它会做一些步骤,就像没有一样。到目前为止,我对powershell还不是很熟练。下面是我得到的,如果有人能帮我的话!谢谢

$dir = "C:UsersuserDownloads*.pdf"
$names = "C:UsersuserDownloadscontent.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
}

要改写你想要的内容。。。

  1. "C:UsersuserDownloads"中搜索所有PDF
  2. "C:UsersuserDownloadscontent.txt"中的名称进行比较。
    • 如果它们已经在列表中;其他东西">
    • 如果没有,是否将名称添加到"C:UsersuserDownloadscontent.txt"

假设我的假设是正确的,您可以使用以下内容:

$fileNames = Get-Content -Path ($path = 'C:UsersuserDownloadscontent.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
}
}

在第一个if语句中,将检查文件以查看它们是否已在列表中。如果文件名已经在列表中,则显示一条这样的消息-然后,在同一个if主体中,您可以为找到的文件添加其余代码。

else语句中,未找到的文件的名称将添加到列表中。


一旦指定了要对未找到的文件采取的适当操作,就从Add-Content中删除-WhatIf公共/安全参数

您可以尝试为此使用正则表达式:

$inNames = Select-String -Path "$names" -Pattern ('^' + "$file" + '$') -CaseSensitive -List

这将返回仅由"$file"组成的"$names"文件中的第一行,区分大小写。

您可能还想在字符串中加载内容文件,这样命令就不必每次运行时都打开它。用于该用途:

$namesContent = Get-Content -Path "$names"
$inNames = $namesContent | Select-String -Pattern ('^' + "$file" + '$') -CaseSensitive -List

最新更新