Powershell 分割路径:无法将参数绑定到参数';路径';因为它在构造函数中为null
我现在正试图在PowerShell中获得一些课程。 我正在尝试运行以下代码:Powershell 分割路径:无法将参数绑定到参数';路径';因为它在构造函数中为null,powershell,class,scripting,Powershell,Class,Scripting,我现在正试图在PowerShell中获得一些课程。 我正在尝试运行以下代码: class myClass{ [String] $path myClass(){ $this.path = Split-Path -Parent $MyInvocation.MyCommand.Definition } } $a = [myClass]::new() #$a.tokenpath #Split-Path -Parent $MyInvocation.MyComma
class myClass{
[String] $path
myClass(){
$this.path = Split-Path -Parent $MyInvocation.MyCommand.Definition
}
}
$a = [myClass]::new()
#$a.tokenpath
#Split-Path -Parent $MyInvocation.MyCommand.Definition
但我得到了以下错误:
Split-Path : Cannot bind argument to parameter 'Path' because it is null.
如果我在类外运行同一行代码,我不会得到错误。
有人知道为什么吗?
$MyInvocation.MyCommand
在类中似乎不起作用。但是,$psscriptroot
的工作原理与拆分路径-父级$MyInvocation.MyCommand.Definition
更新代码:
class myClass{
[String] $path
myClass(){
$this.path = $PSScriptRoot
}
}
$MyInvocation.MyCommand
在类中似乎不起作用。但是,$psscriptroot
的工作原理与拆分路径-父级$MyInvocation.MyCommand.Definition
更新代码:
class myClass{
[String] $path
myClass(){
$this.path = $PSScriptRoot
}
}
那很方便。感谢您的回答:)可以在powershell的类构造函数中使用类方法。我试图按照以下思路做一些事情:
classmyclass{[Void]myMethod(){Write Host“Hello World!”}myClass(){[myClass]::myMethod()}}$test=[myClass]::new()
但是我得到了以下错误:方法调用失败,因为[myClass]不包含名为“myMethod”的方法。方法调用将是$this.myMethod()而不是[myclass]::myMethod()$MyInvocation.MyCommand在非常方便的函数内部也不起作用。感谢您的回答:)可以在powershell的类构造函数中使用类方法。我试图按照以下思路做一些事情:classmyclass{[Void]myMethod(){Write Host“Hello World!”}myClass(){[myClass]::myMethod()}}$test=[myClass]::new()
但是我得到了以下错误:方法调用失败,因为[myClass]不包含名为“myMethod”的方法。方法调用将是$this.myMethod()而不是[myclass]::myMethod()$MyInvocation.MyCommand在函数内部也不起作用