重命名文件夹并在 PowerShell 中创建新文件夹

Renaming a Folder and create a new folder in PowerShell

我的文件夹结构:C:\example\latest。 我想检查最新的子文件夹是否已经存在。如果是这样,我想将其重命名为 latest_MMddyyyy,然后创建一个名为 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' 的参数,然后重试。

我做错了什么?

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

您正在使用 -ItemType 但未为其提供值,请使用:

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

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

正如 指出的那样,您缺少 -ItemType 的参数,而是在其后跟 另一个 参数 -Type,实际上,它是 -ItemType 别名 - 所以 删除 either -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 generally 只接受 file/directory name 作为 -NewName 参数,而不是 full路径;如果其父路径与输入项的父路径 相同 ,则只能使用完整路径 - 换句话说,如果路径不会导致 重命名项目的不同位置(您需要 Move-Item cmdlet 来实现)。

    • Split-Path -Leaf $localPath 提供了一种方便的方法来提取 last 路径组件,无论输入路径是否有尾随 \ .
      在这种情况下:latest

    • 或者,$localPath -replace '\$' 总是 return 没有尾随 \.
      path 在这种情况下: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

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

试试这个

$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

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

Rename-Item Old_Folder_Name New_Folder_Name