我正在编写一组 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 上。
最佳答案
我建议您多复习一下 PowerShell 的语法,因为其中有很多错误。 PowerShell 与 C# 截然不同,您似乎做出了很多假设。 :)
首先,这不是您调用 PowerShell 函数的方式。也不确定为什么要在参数周围添加引号?他们是多余的。如果您修复了函数调用,您的代码应该会按预期运行。
$mypath = getFullPath $loc $folder
然后你的switch语句中有一个分号,这也是错误的。然后,如果您只使用 ''
,则不必转义 $
。 break 也是多余的,因为在这种情况下 return 退出函数。
"192.168.10.10" { return 'E$' }
此外,关于 PowerShell 的一件有趣的事情:您可以去掉 getFullPath
中的返回:
function getFullPath($loc, $folder) {
$drive = getDriveLetter($loc)
"\\$loc\$drive\DATA\$folder"
}
PowerShell 返回未捕获的输出,这一点很重要,它可能是许多隐蔽错误的原因。
关于Powershell 函数被传递了太多参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45629694/