用于填写开始部分的 Powershell 脚本和路径

Powershell script to fill out Start in section with path

尝试让 powershell 通过以下方式填写快捷方式文件中的 "Start in" 部分:

$Shortcut.WorkingDirectory

到目前为止的脚本:

$file = pwd
# Create a Shortcut with Windows PowerShell
$TargetFile = "$file\file.vbs"
$ShortcutFile = "$file\file.lnk"
$WScriptShell = New-Object -ComObject WScript.Shell
$Shortcut = $WScriptShell.CreateShortcut($ShortcutFile)
$Shortcut.TargetPath = $TargetFile
$Shortcut.WorkingDirectory = $file

这是我收到的错误。

Exception setting "WorkingDirectory": Cannot convert the "C:\PATH\TO\FOLDER" value of type "PathInfo" to type "string".
At line:8 char:5
+     $Shortcut.WorkingDirectory = $file
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], SetValueInvocationException
    + FullyQualifiedErrorId : RuntimeException
    $Shortcut.Save()

不胜感激。 :)

pwd 是命令 Get-Location 的别名。它 returns 一个 PathInfo 具有许多指向当前目录的属性的对象。 Path 属性 包含路径字符串。

因此,您需要从 pwd 输出或 $file:

访问 Path 属性
$file = (pwd).Path
$TargetFile = "$file\file.vbs"
$ShortcutFile = "$file\file.lnk"
$WScriptShell = New-Object -ComObject WScript.Shell
$Shortcut = $WScriptShell.CreateShortcut($ShortcutFile)
$Shortcut.TargetPath = $TargetFile
$Shortcut.WorkingDirectory = $file

自动变量$pwd 还包含具有许多指向当前目录的属性的PathInfo 对象。您可以使用 $pwd.Path:

访问相同的值
$file = $pwd.Path

附加信息:

您可以使用 Get-Member 命令查看属性和类型信息:

$pwd | Get-Member

   TypeName: System.Management.Automation.PathInfo

Name         MemberType Definition
----         ---------- ----------
Equals       Method     bool Equals(System.Object obj)
GetHashCode  Method     int GetHashCode()
GetType      Method     type GetType()
ToString     Method     string ToString()
Drive        Property   System.Management.Automation.PSDriveInfo Drive {get;}
Path         Property   string Path {get;}
Provider     Property   System.Management.Automation.ProviderInfo Provider {get;}
ProviderPath Property   string ProviderPath {get;}

每个 属性 值都可以使用成员访问运算符 . 和语法 object.Property 直接访问。 Select-Object -ExpandProperty Property 语法也是检索 属性 值的一种流行方式。

# Member Access Method
$pwd.Path
C:\MyCurrentPath

# Select-Object Method

$pwd | Select-Object -ExpandProperty Path
C:\MyCurrentPath

PathInfo 对象包含一个 ToString() 覆盖方法,该方法 returns 路径作为字符串。

$pwd.ToString()
C:\MyCurrentPath

(pwd).ToString()
C:\MyCurrentPath