是否有一个 PowerShell 命令来复制和重命名文件? [英] Is there a single PowerShell command to copy and rename files?

查看:31
本文介绍了是否有一个 PowerShell 命令来复制和重命名文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下命令将文件从网络共享复制到基于 CSV 文件的本地硬盘驱动器.

I am using the following command to copy files from a network share to my local hard drive based on a CSV file.

import-csv C:\TEST\test.csv | foreach {copy-item -path $_.npath -destination 'C:\TEST\'}

下一步是使用不同的 CSV 文件根据当前文件名重命名这些文件.

The next step would be to then use a different CSV file to rename these files based on their current file name.

是否有一个命令可以让我复制和项目并重命名它?

Is there a command that will allow me to copy and item and rename it as well?

推荐答案

如果您的 CSV 文件包含两列 oldfilepath 和 newfilename,那么您可以使用以下内容.

If you have a CSV containing two columns, oldfilepath and newfilename, then you can use the following.

Import-Csv C:\test.csv | % { Copy-Item -Path $_.oldfilepath -Destination "C:\TEST\$($_.newfilename)" }

注意 $_.newfilename 是如何封装在 $() 中的.那是因为 $_.newfilename 是一个表达式(因为我们从变量中获取一个属性),而不是一个变量.$() 告诉 PowerShell 在字符串中使用它之前先解决它.如果我们不使用它,它将使用该行的整个 csv 对象 ($_) 作为字符串并返回错误.

Notice how the $_.newfilename is encapsulated inside a $(). That's because $_.newfilename is an expression (since we are getting a property out of the variable), and not a variable. $() tells PowerShell to solve the expression before using it in the string. If we don't use it, it would have used the whole csv-object for that row($_) as a string and returned an error.

这篇关于是否有一个 PowerShell 命令来复制和重命名文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆