Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops Powershell循环正在工作,但仍返回错误_Loops_Powershell - Fatal编程技术网

Loops Powershell循环正在工作,但仍返回错误

Loops Powershell循环正在工作,但仍返回错误,loops,powershell,Loops,Powershell,我有以下powershell脚本,用于在文件移动到目标文件夹后以当前日期重命名该文件: ##DateStamp $DateStamp = get-date -uformat "%Y%m%d" $files = @(get-childitem C:\PowershellTesting\FolderTwo\*.csv) foreach ($file in $files) { get-childitem | rename-item $file -NewName {"Compan

我有以下powershell脚本,用于在文件移动到目标文件夹后以当前日期重命名该文件:

##DateStamp

$DateStamp = get-date -uformat "%Y%m%d"

$files = @(get-childitem C:\PowershellTesting\FolderTwo\*.csv)

    foreach ($file in $files)    
{
 get-childitem | rename-item $file -NewName {"CompanyName" + $DateStamp + ".csv"}}
脚本实际上可以重命名文件,尽管它仍然会多次重复出现此错误:

rename-item : Cannot rename because item at 'C:\PowershellTesting\FolderTwo\17Feb17082308_CompanyName_20170217.csv' does not exist.
At line:11 char:18
我猜这是因为文件重命名后循环没有退出,因为只有一个循环。考虑到它的工作原理,我猜我错过了一些简单的东西,可以帮助我摆脱错误

对于每个csv,您的工作目录将返回并传递到此处的
重命名项
。删除
Get ChildItem
,只需使用rename item,因为您的文件对象仍然是
$file
。这将是你想要的最小的改变

$file | rename-item -NewName {"CompanyName" + $DateStamp + ".csv"}}
我会提醒您重命名逻辑,因为每个文件都会尝试获得相同的名称。如果同一目录中存在任何冲突,则会发生冲突

这可以缩短为以下内容。请记住,上述警告仍然适用

$DateStamp = get-date -uformat "%Y%m%d"
Get-ChildItem "C:\PowershellTesting\FolderTwo\*.csv" | 
    Rename-Item  -NewName {"CompanyName" + $DateStamp + ".csv"}

如果我删除了get ChildItem,那么它根本不起作用,并给出以下错误:重命名项:无法计算参数“NewName”,因为它的参数被指定为脚本块,并且没有输入。一个脚本块在没有输入的情况下是无法计算的,我认为文件一旦发送就会被删除,所以当脚本运行时,文件夹中应该只有一个文件。
$DateStamp = get-date -uformat "%Y%m%d"
Get-ChildItem "C:\PowershellTesting\FolderTwo\*.csv" | 
    Rename-Item  -NewName {"CompanyName" + $DateStamp + ".csv"}