2017-02-21 73 views
1

我遇到了一个我写过的脚本(假设)执行以下操作的脚本。 我有一个文件夹与一些csv文件,我想复制最新的文件与公司名称到另一个文件夹,并重命名它。Powershell - 拷贝后重命名文件

它是在当前格式:

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的顺序。目标中还有其他文件(文本文件,批处理文件),以防影响。 任何帮助,我会去哪里错将不胜感激。

+4

'$ file'没有被定义和不需要。该cmdlet从管道获取文件参数。 – wOxxOm

+0

完美...总是有点简单!谢谢。 – Ricky

回答

2

正如wOxxOm回答的那样,您需要从Rename-Item中删除$file,因为它未定义,并且cmdlet已通过管道接收输入对象。

我还建议您通过将fileinfo对象复制到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"} 
1

您可以重命名并复制一个命令。只需使用Copy-Item Command并将新路径和名称作为-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"}