iT邦幫忙

0

PowerShell Test-Path 使用請益

  • 分享至 

  • xImage

請教各位大神,小弟是PowerShell新手,由於小弟近期要進行File Server上頭的大量資料移動,
因此想透過PowerShell的腳本執行,不過前期進行測試的時候遇到了點問題,
由於事前期測試,我先將測試用的路徑寫死成陣列,
再透過迴圈的方式進行執行,

程式碼如下:

$FilePath
$DestinationPath = "\\192.168.1.50\測試目的地資料夾"
$PathArr  = {\\192.168.1.50\路徑測試資料夾\3.bmp},{\\192.168.1.50\路徑測試資料夾\file2.pptx},{\\192.168.1.50\路徑測試資料夾\檔案1.rtf}

$i=0

while($i-lt $PathArr.Length)
{
    $FilePath = $PathArr[$i]
    if(Test-Path $FilePath)
    {
        Move-Item $FilePath -Destination $DestinationPath
    }
    else
    {
        echo "移動失敗"
    }
    $i++
}

 if( Test-Path \\192.168.1.50\路徑測試資料夾\3.bmp )
    {
        #echo $FilePath
        echo "成功"
    }
 #測試路徑是否正常

實際執行過後,發現Test-Path $FilePath的結果都是false,
但最下面我直接不透過字串,直接使用路徑卻是成功的,
爬文許久還是沒找到解答,希望版上大大們能給小弟一些指導,感謝萬分。

nwm310 iT邦新手 4 級 ‧ 2022-03-28 19:22:57 檢舉
把那三個檔案路徑的外圍大括弧,改成單引號
xenic719 iT邦新手 4 級 ‧ 2022-03-29 10:44:58 檢舉
謝謝nwm310大,成功了,感謝指導
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
runan5678
iT邦研究生 1 級 ‧ 2022-03-28 16:21:10
最佳解答

$FilePath = $PathArr[$i].tostring()
試試看

xenic719 iT邦新手 4 級 ‧ 2022-03-28 16:40:02 檢舉

感謝runan5678大指導,不過結果一樣是False,我猜想與字串無關,因為我嘗試透過echo去輸出陣列,可以完整輸出每一個路徑,但Test-Path就是判斷為False。

runan5678 iT邦研究生 1 級 ‧ 2022-03-28 17:09:27 檢舉

測試使用提供的語法,會在執行的時候就出現錯誤,是沒有辦法跑到確認成功或失敗的步驟,可能是其他的問題

0
qpowjohn
iT邦新手 4 級 ‧ 2022-03-29 08:57:30

你先試試看get-content能不能看到,說不定是權限問題

qpowjohn iT邦新手 4 級 ‧ 2022-03-29 08:58:47 檢舉

while($i-lt $PathArr.Length)
這邊是不是錯了,-lt前面要空格

xenic719 iT邦新手 4 級 ‧ 2022-03-29 10:46:57 檢舉

感謝qpowjohn大,因為我是Domain admin,權限沒問題,while迴圈也有正常執行,目前問題已解決,感謝協助!

我要發表回答

立即登入回答