使用PowerShell重命名文件夹并创建新文件夹

4

我的文件夹结构:C:\example\latest。 我想要检查子文件夹最新的是否已经存在。如果存在,我想把它重命名为latest_MMddyyyy,然后创建一个新的文件夹叫做latest。 如果不存在latest,则直接创建该文件夹。

这是我已经有的:

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”的参数,然后重试。

我做错了什么?

4个回答

4

抛出错误: Missing an argument for parameter 'ItemType'. Specify a parameter of type 'System.String' and try again.

正如Deadly-Bagel的有用回答所指出的,您缺少对-ItemType的参数,并且跟随它的是另一个参数-Type,实际上,它是-ItemType的别名 - 因此删除任一-ItemType-Type都可以工作

要查找参数的别名,请使用类似于(Get-Command New-Item).Parameters['ItemType'].Aliases的内容

将我的最新文件夹重命名为_MM-dd-yyyy,但我想要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

请注意,如果您在同一天内运行此脚本多次,则在重命名时会出现错误(这很容易处理)。

3

尝试这个

$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

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

您正在使用-ItemType,但未提供值,请使用以下内容:

您正在使用-ItemType,但未提供值,请使用以下内容:

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

-1

要重命名文件夹,请使用以下命令:Rename-Item,例如:

Rename-Item Old_Folder_Name New_Folder_Name


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接