2017-02-08 236 views
1

我的文件夹结构:C:\ example \ latest。 我想检查子文件夹的最新版本是否已经存在。如果有,请将其重命名为latest_MMddyyyy,然后创建一个名为latest的新文件夹。 如果它还没有最新的,那么简单创建文件夹。重命名文件夹并在PowerShell中创建新文件夹

这是我有:

param (
    $localPath = "c:\example\latest\"              #" 
) 

     #Creating a new directory if does not exist 
     $newpath = $localPath+"_"+((Get-Date).AddDays(-1).ToString('MM-dd-yyyy')) 
     If (test-path $localPath){ 
      Rename-Item -path $localpath -newName $newpath 
     } 
     New-Item -ItemType -type Directory -Force -Path $localPath 

这是做两件事情:

  1. 重命名我最新的文件夹_MM-DD-YYYY但我想它重新命名为“latest_MM-DD -yyyy“
  2. 抛出一个错误:缺少参数'ItemType'的参数。指定一个类型为“System.String”的参数并重试。

我做错了什么?

回答

1

Throws an error: Missing an argument for parameter 'ItemType'. Specify a parameter of type 'System.String' and try again.

由于Deadly-Bagel's helpful answer指出,你错过了一个参数-ItemType,而是遵循它与另一个参数,-Type,其实是别名对于-ItemType - 所以remov ing 要么-ItemType-Type将工作

要找到一个参数的别名,使用类似(Get-Command New-Item).Parameters['ItemType'].Aliases

Renames my latest folder to _MM-dd-yyyy , but I want latest_MM-dd-yyyy .

  • 您可以直接追加日期字符串$localPath,其中有一个尾随\,所以$newPath看起来像'c:\example\latest\_02-08-2017',这不是意图。

  • 确保$localPath有没有尾随\解决问题,但千万注意,Rename-Item一般只接受一个文件/目录-NewName的说法,不是一个完整路径;你只能逃脱一个完整路径,如果它的父路径是相同作为输入项目的 - 换句话说,你可以,如果它不会在不同的位置导致重命名的项目只指定路径(你需要的Move-Item cmdlet来实现这一点)。

    • Split-Path -Leaf $localPath提供提取最后路径组件的一种便捷方式,输入路径是否有尾随\
      在这种情况下:latest

    • 另外,$localPath -replace '\\$'总是会返回一个路径无尾\
      在这种情况下:c:\example\latest

如果我们把它们放在一起:

param (
    $localPath = "c:\example\latest\"   #"# generally, consider NOT using a trailing \ 
) 

# Rename preexisting directory, if present. 
if (Test-Path $localPath) { 
# Determine the new name: the name of the input dir followed by "_" and a date string. 
# Note the use of a single interpolated string ("...") with 2 embedded subexpressions, 
# $(...) 
$newName="$(Split-Path -Leaf $localPath)_$((Get-Date).AddDays(-1).ToString('MM-dd-yyyy'))" 
Rename-Item -Path $localPath -newName $newName 
} 

# Recreate the directory ($null = ... suppresses the output). 
$null = New-Item -ItemType Directory -Force -Path $localPath 

需要注意的是,如果你在当天运行此脚本超过一次多,你会在重命名时遇到错误(这很容易处理)。

2
New-Item -ItemType -type Directory -Force -Path $localPath 

您使用-ItemType而不是提供一个值,使用:

New-Item -ItemType Directory -Force -Path $localPath 
2

试试这个

$localPath = "c:\temp\example\latest" 

#remove last backslash 
$localPath= [System.IO.Path]::GetDirectoryName("$localPath\")        #" 

#create new path name with timestamp 
$newpath ="{0}_{1:MM-dd-yyyy}" -f $localPath, (Get-Date).AddDays(-1) 

#rename old dir if exist and recreate localpath 
Rename-Item -path $localpath -newName $newpath -ErrorAction SilentlyContinue 
New-Item -ItemType Directory -Force -Path $localPath 
0

要重命名文件夹,使用命令:Rename-Item e.g

Rename-Item Old_Name New_Name