PowerShell函数如何正确传入两个字符串参数并拼接路径?
问题根因
PowerShell 的函数调用语法和传统C系语言存在本质差异:
当前写法SearchFile($dir,$file),会被PowerShell解析为将括号内$dir,$file组成的二元数组作为单个参数传递给函数的第一个形参$dir,第二个形参$file未接收到任何传值,因此才会出现$dir显示两个值拼接、$file为空的异常输出。
修复方案
1. 修正函数参数传递逻辑
PowerShell 调用函数时,参数直接用空格分隔即可,不要添加包裹所有参数的括号、不要用逗号分隔单个参数:
- 错误写法:
SearchFile($dir,$file) - 正确写法1(位置传参):
SearchFile $dir $file - 正确写法2(显式命名传参,可读性更强、参数顺序不匹配也不会出错):
SearchFile -dir $dir -file $file
2. 使用原生方法完成跨平台路径拼接
不要手动拼接路径字符串、手动硬编码路径分隔符(Windows/macOS/Linux的路径分隔符存在差异,手动拼接极易出现格式错误),使用PowerShell内置的Join-Path方法完成路径拼接,可自动适配当前系统的路径规则。
修正后的完整代码
自定义函数库(library.ps1)
function SearchFile($dir, $file) { "dir is $dir" "file is $file" # 替换原有手动字符串拼接逻辑 $full = "full is $(Join-Path -Path $dir -ChildPath $file)" $full }
调用脚本(worker.ps1)
. /home/nicholas/powershell/functions/library.ps1 $dir = "/home/nicholas/powershell/regex" $file = "a.log" # 调用函数,两种正确写法二选一即可 SearchFile $dir $file # SearchFile -dir $dir -file $file
修正后的预期输出
posh> pwsh ./worker.ps1 dir is /home/nicholas/powershell/regex file is a.log full is /home/nicholas/powershell/regex/a.log
内容的提问来源于stack exchange,提问作者Nicholas Saunders
相关产品推荐
相关产品推荐

