iT邦幫忙

0

powershell 資料夾路徑和copy問題(已解決)

要達到的目的是
將一個固定路徑底下的最新資料夾(包含底下檔案)copy到其他目錄底下
最新資料夾名稱會變動
我遇到的狀況是無法透過取得資料夾名稱組成新的路徑

#來源路徑
 $srcpath = 'C:\Users\jiff\Documents\LearnData\'
 #切換到來源目錄
 cd $srcpath
 #取得來源目錄底下最新的資料夾名稱
 $result = Get-ChildItem | ?{ $_.PsIsContainer } |Sort-Object -Property LastWriteTime -Descending | select -first 1 | Select-Object -Property Name

或者是有其他方式可以達成
請指點 感謝

查到這篇文章
https://ithelp.ithome.com.tw/questions/10191247?sc=pt
才知道有可能是物件問題
將他印出來測試就可以將路徑組合了

  $srcpath = 'C:\Users\jiff\Documents\LearnData\'
 cd $srcpath
 $files = get-childitem -Directory |Sort-Object -Property LastWriteTime -Descending | select -first 1
foreach ($file in $files) 
{
	$result = $file.Name
    #路徑組合方式兩種
    #$dirpath = [io.path]::combine($srcpath,$result)
	$dirpath = Join-Path $srcpath $result
	$dirpath
	cd $dirpath
}
#用ForEach-Object
 $srcpath = 'C:\Users\jiff\Documents\LearnData\'
 cd $srcpath
get-childitem -Directory |Sort-Object -Property LastWriteTime -Descending | select -first 1 |ForEach-Object {$dirpath = Join-Path $srcpath $_.Name;$dirpath;cd $dirpath}

最後的成果

#將srcpath目錄底下最新的資料夾複製到dispath
 $srcpath = 'C:\Users\jiff\Documents\LearnData\'
 $dispath = 'C:\Users\jiff\Desktop\'
get-childitem -Path $srcpath -Directory |Sort-Object -Property LastWriteTime -Descending | select -first 1 |ForEach-Object {Copy-Item $_.Name -Recurse $dispath}
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答