我写的一个脚本(应该)执行以下操作时遇到了持续的问题。我有一个包含多个csv文件的文件夹,我想将带有公司名称的最新文件复制到另一个文件夹中,并对其重命名。
格式为当前格式:
21Feb17070051_CompanyName_Sent21022017我希望它采用以下格式:
CompanyName21022017因此,我有以下powershell脚本来完成此操作:
## Declare variables ##
$DateStamp = get-date -uformat "%Y%m%d"
$csv_dest = "C:\Dest"
$csv_path = "C:\Location"
## Copy latest Company CSV file ##
get-childitem -path $csv_path -Filter "*Company*.csv" |
where-object { -not $_.PSIsContainer } |
sort-object -Property $_.CreationTime |
select-object -last 1 |
copy-item -Destination $csv_dest
## Rename the file that has been moved ##
get-childitem -path $csv_dest -Filter "*Company*.csv" |
where-object { -not $_.PSIsContainer } |
sort-object -Property $_.CreationTime |
select-object -last 1 | rename-item $file -NewName {"Company" + $DateStamp + ".csv"} 该文件似乎复制正常,但重命名失败-
Rename-Item : Cannot bind argument to parameter 'Path' because it is null.
At C:\Powershell Scripts\MoveCompanyFiles.ps1:20 char:41
+ select-object -last 1 | rename-item $file -NewName {"CompanyName" + $DateSt ...我认为这与powershell的工作顺序有关,或者是它在$file变量中看不到.csv的事实。目标中还有其他文件(文本文件、批处理文件),以防影响到某些内容。在我出错的地方,任何帮助都将不胜感激。
发布于 2017-02-21 23:22:35
正如wOxxOm回答的那样,您需要从Rename-Item中删除$file,因为它没有定义,并且cmdlet已经通过管道接收到了输入对象。
我还建议您通过将复制文件的fileinfo-object传递给Rename-Item来组合这两个操作。例如:
## Declare variables ##
$DateStamp = get-date -uformat "%Y%m%d"
$csv_dest = "C:\Dest"
$csv_path = "C:\Location"
## Copy and rename latest Company CSV file ##
Get-ChildItem -Path $csv_path -Filter "*Company*.csv" |
Where-Object { -not $_.PSIsContainer } |
Sort-Object -Property CreationTime |
Select-Object -Last 1 |
Copy-Item -Destination $csv_dest -PassThru |
Rename-Item -NewName {"Company" + $DateStamp + ".csv"}发布于 2017-08-27 02:21:30
您可以在单个命令中重命名和复制。只需使用Copy-Item命令并给出新的路径和名称作为-Destination参数值。它将复制并重命名该文件。你可以在下面找到一个例子。
$source_path = "c:\devops\test"
$destination_path = "c:\devops\test\"
$file_name_pattern = "*.nupkg"
get-childitem -path $source_path -Filter $file_name_pattern |
Copy-Item -Destination { $destination_path + $_.Name.Split("-")[0] + ".nupkg"}https://stackoverflow.com/questions/42366551
复制相似问题