2017-02-08 233 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