Powershell 使用函数设置脚本文件夹位置失败
我用一段代码创建了一个函数,该代码在脚本中运行良好,但在转换为函数时失败 代码将脚本所在的位置设置为当前位置Powershell 使用函数设置脚本文件夹位置失败,powershell,Powershell,我用一段代码创建了一个函数,该代码在脚本中运行良好,但在转换为函数时失败 代码将脚本所在的位置设置为当前位置 Function Set-ScriptFolder { <# .SYNOPSIS Sets the location to the folder where the script folder resides. .DESCRIPTION Sets the location to the folder where
Function Set-ScriptFolder
{
<#
.SYNOPSIS
Sets the location to the folder where the script folder resides.
.DESCRIPTION
Sets the location to the folder where the script folder resides.
.EXAMPLE
Set-ScriptFolder
.EXAMPLE
Set-ScriptFolder
#>
$location = Split-Path $MyInvocation.MyCommand.Path
set-location $location
}
你知道如何转换吗
$location = Split-Path $MyInvocation.MyCommand.Path
set-location $location
去参加一个活动
如果你看一下,你会看到
$MyInvocation
仅为脚本、函数和脚本块填充。
您可以使用System.Management.Automation.InvocationInfo中的信息
$MyInvocation在当前脚本中返回的对象,例如路径
脚本的文件名($MyInvocation.MyCommand.Path
)或
函数($MyInvocation.MyCommand.Name
)来标识当前命令
您可以在函数中看到$MyInvocation.MyCommand.Name
的输出将返回:
Set-ScriptFolder
替代解决方案
您可以改用$PSScriptRoot
Set-Location $PSScriptRoot
这也应该在函数内部工作。如果愿意,您也可以使用$MyInvocation
的属性PSScriptRoot
,只要您拥有PowerShell 3.0或更高版本
Set-Location $MyInvocation.PSScriptRoot
仅用于一行的函数似乎有点过头了
$MyInvocation
在函数中是函数的调用信息,不是吗?我想这就是问题所在。这意味着你可以通过脚本将参数传递到函数中,我想。。。但是为什么要麻烦呢?谢谢,设置位置$MyInvocation.PSScriptRoot可以工作,但是$PSScriptRoot不能工作。@RalJans请确保您确实保存了文件,而不是在未保存的文件中从ISE运行它$PSScriptRoot
仅在从文件运行时有效。
Set-Location $MyInvocation.PSScriptRoot