[英]How to create 2 loops?
I have a csv file with NetworkID and NewFileName field. 我有一个带有NetworkID和NewFileName字段的csv文件。 and I have bunch of files on a fileshare.
我在文件共享上有一堆文件。 The file name under the file share named after domain_networkid_Lthumb.jpg.
以domain_networkid_Lthumb.jpg命名的文件共享下的文件名。
The idea is read each line from csv then find the file using contains (i guess). 这个想法是从csv的每一行读取的,然后使用contains(我猜)找到文件。 If a file is found that at least contains networkid_lthumb then rename this file to NewFileName.jpg.
如果找到至少包含networkid_lthumb的文件,则将此文件重命名为NewFileName.jpg。
What is the best way to do this? 做这个的最好方式是什么? I have following code.
我有以下代码。 and I just want to make it's efficient.
我只是想提高效率。
# Renames file based on CSV
$csvFile = Import-csv 'c:\userdata.csv'
$files = Get-ChildItem "c:\eePics\"
foreach($user in $csvFile)
{
$account = $user.networkid
$keyword = $account + "_LThumb"
$file = Get-Content $files.FullName
$ContainsWord = $file | %{$_ -match $keyword}
if($ContainsWord -contains $true)
{
Rename-Item $_.name -NewName $user.NewFileName
}
}
If i understood correctly what you are trying to achieve this should work: 如果我正确理解了您要实现的目标,则应正常工作:
$csvFile = Import-csv "C:\userdata.csv"
$filePath = "C:\eepics\"
$destination = "C:\example\folder\"
foreach($user in $csvFile){
$filename = $user.networkid + "_LThumb"
Get-Childitem $filePath | where {$_.Name -match $filename} | Rename-Item -NewName $user.NewFileName
Copy-Item $filePath$($user.NewFileName) -Destination $destination
}
Note that the NewFileName in your csv has to contain the File-Extension (eg ".jpg") 请注意,csv中的NewFileName必须包含文件扩展名(例如“ .jpg”)
-contains
is used to test if a set (for example an array) contains a value. -contains
用于测试集合(例如数组)是否包含值。 boolean comparisons like you are trying to do in your if statement should be done like this: 布尔比较,例如您要在if语句中尝试执行的比较,如下所示:
if($variable){}
If $variable
is True the block will be executed 如果
$variable
为True,则将执行该块
Regarding your code: 关于您的代码:
$file = Get-Content $files.FullName
will actually get the content (and if i say content i mean it) of all files in the directory C:\\eepics\\ 实际上将获取目录C:\\ eepics \\中所有文件的内容(如果我说是内容,我是说真的)
$ContainsWord = $file | %{$_ -match $keyword}
will cycle through all contents of all files you got line by line and see if something matches $keyword 将逐行循环浏览所有文件的所有内容,并查看是否有匹配$ keyword的文件
Update: added code to copy the file after renaming because of user request 更新:由于用户请求,添加了重命名后复制文件的代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.