Vor*_*t3x 2 powershell alias function
我在文件 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.")
}
}
Run Code Online (Sandbox Code Playgroud)
我点从命令行调用它
. .\myfunc.ps1
然后打电话
Set-Util somedirectory
别名在函数中设置正确,但我无法在这里访问它
我的实用程序
我应该导出别名,因为范围仅在方法中吗?我尝试使用 Export-ModuleMember 执行此操作,但出现错误,提示该 cmdlet 只能从模块中调用。
你不能这样做,因为在调用函数之前不会设置别名,并且当函数被调用时,别名的范围是函数范围,所以当函数完成运行时 - 别名消失了。
如果您希望别名继续存在,请指定值为“global”的 use scope 参数