[英]Powershell alias inside function not available outside
我在文件myfunc.ps1中有一个powershell函数
function Set-Util ($utilPath ) {
if(Test-Path($utilPath) ){
$fullPath = Join-Path -Path $utilPath "util.exe"
set-alias MyUtil $fullPath
#echo "Path set to $fullPath"
}else {
throw (" Error: File not found! File path '$fullPath' does not exist.")
}
}
我用命令行从命令行调用它
。 。\\ myfunc.ps1
然后打电话
设置公用目录
别名已在函数中正确设置,但我无法在此处访问它
MyUtil
是否应该导出别名,因为范围仅在方法中? 我尝试使用Export-ModuleMember进行此操作,但收到一条错误消息,指出只能从insdie模块调用cmdlet。
您不能这样做,因为在调用函数之前不会设置别名,并且在调用函数时,别名的作用域范围是函数作用域,因此当函数完成运行时,别名就消失了。
如果希望别名保留下来,则将use scope参数指定为'global'
别名只能指向cmdlet ,而不能指向cmdlet(对象)的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.