2017-08-11 130 views
3

我在寫一組PowerShell腳本來監視各種文件夾的大小。我遇到了一個錯誤,我不知道是什麼原因造成的。Powershell函數傳遞太多參數

下面是代碼,與Write-Host顯示什麼,我期待和什麼變量$ip$loc實際上包含:

function getDriveLetter($ip) { 
    Write-Host $ip # prints: 192.168.10.10 myfolder1\myfolder2\ 
         # expected: 192.168.10.10 
    switch($ip) { 
     "192.168.10.10" {return "E`$"; break} 
     "192.168.10.20" {return "D`$"; break} 
     default {"Unknown"; break} 
    } 
} 

function getFullPath($loc,$folder) { 
    Write-Host $loc # prints: 192.168.10.10 myfolder1\myfolder2\ 
         # expected: 192.168.10.10 
    $drive = getDriveLetter("$loc") 
    $str = "\\$loc\$drive\DATA\$folder" 
    return $str 
} 

function testPath($loc,$folder) { 
    $mypath = getFullPath("$loc","$folder") 
    if (Test-Path $mypath) { 
     return $true 
    } else { 
     return $false 
    } 
} 

當我運行命令:

testPath("192.168.10.10","myfolder1\myfolder2\") 

我越來越一個「假」的結果,但如果我運行:

Test-Path "\\192.168.10.10\E`$\DATA\myfolder1\myfolder2\" 

該命令返回True(因爲它應該)。


我錯過了什麼?我試過強迫變量設置爲:

$mypath = getFullPath -loc "$loc" -folder "$folder" 

但是沒有變化。如果它改變了任何東西,這是在Powershell版本4上。

回答

3

我建議你多複習一下PowerShell的語法,因爲那裏有很多錯誤。 PowerShell與C#完全不同,你似乎做了很多假設。 :)

首先,這不是你如何調用PowerShell函數。也不知道爲什麼你添加引號的參數?它們是多餘的。如果您修復函數調用,您的代碼應該按預期工作。

$mypath = getFullPath $loc $folder 

再有就是在你的switch語句,這也是錯誤的分號。然後,如果您只使用'',則不必轉義$。休息也是多餘的,因爲在這種情況下返回退出功能。

"192.168.10.10" { return 'E$' } 

此外,關於PowerShell的一個有趣的事情:你可以只擺脫回報的getFullPath

function getFullPath($loc, $folder) { 
    $drive = getDriveLetter($loc) 
    "\\$loc\$drive\DATA\$folder" 
} 

PowerShell會返回未捕獲的輸出,要知道這是非常重要的,它可以是許多晦澀的錯誤的原因。

+0

這解決了這個問題,太感謝你了!我還會用其他建議更新腳本(以及其他一些其他的內容)。我希望Powershell支持帶括號的多個參數,我覺得空格分隔的參數看起來不那麼幹淨。 – Elmepo

2

問題在於你如何調用你的函數。函數參數是在PowerShell中用空格分隔的,不要使用括號來包圍參數。

getFullPath $loc $folder 

當您將參數包含在括號中時,您將創建一個包含兩個值的數組,並將該數組作爲第一個參數傳遞。

getFullPath($loc, $folder) 

此線通過含有兩個字符串@($loc, $folder)作爲第一個參數的陣列,然後,因爲有上線沒有其他參數,它傳遞$null到秒。在函數內部,數組然後被用作字符串,這是您觀察到的行爲。

2

問題是如何將參數傳遞給函數。 請參閱上面的鏈接的詳細信息: How do I pass multiple parameters into a function in PowerShell?

function getDriveLetter() { 
    param($ip) 
    switch($ip) { 
     "192.168.0.228" {return "E`$"; break} 
     "192.168.10.20" {return "D`$"; break} 
     default {"Unknown"; break} 
    } 
} 

function getFullPath() { 
    param($loc, $folder) 
    $drive = getDriveLetter -ip $loc 
    $str = "\\$loc\$drive\DATA\$folder" 
    return $str 
} 

function testPath() { 
    param($loc, $folder) 
    $mypath = getFullPath -loc $loc -folder $folder 
    if (Test-Path $mypath) { 
     return $true 
    } else { 
     return $false 
    } 
} 
testPath -loc "192.168.10.10" -param "myfolder1\myfolder2\"