提问人:Get-Help 提问时间:10/27/2022 更新时间:10/28/2022 访问量:127
如何在不引用其名称的情况下将 “ 与变量一起使用?
how to use " with a variable without it quoting it as a name?
问:
我一直在尝试编写一个脚本,该脚本涉及创建指向 .ps1 文件的快捷方式。 该脚本的目标是比较两个文件夹,对于出现在文件夹 #1 中但未出现在文件夹 #2 中的任何文件,将创建一个快捷方式,其中包含“powershell.exe -file '$shortcutpath'”,其中 $shortcutpath 是文件本身的位置,并且需要 powershell.exe -file 才能使用 Powershell 启动快捷方式。
这就是我目前所拥有的。附言...有一些行用于删除任何不需要的文件
$sourcelist = Get-ChildItem -path "C:\Users\yo\Documents\Powershell Lab\source" | Get-ItemPropertyvalue -name "name"
$shortcutlist = Get-ChildItem -path "C:\Users\yo\Documents\Powershell Lab\fixes" | Get-ItemPropertyvalue -name "name"
#compare files
$sourceNoShortcutList = Compare-Object -ReferenceObject $sourcelist -DifferenceObject $shortcutlist |Where-Object SideIndicator -eq '=>' |ForEach-Object InputObject
$reqshortcutlist = Compare-Object -ReferenceObject $sourcelist -DifferenceObject $shortcutlist |Where-Object SideIndicator -eq '<=' |ForEach-Object InputObject
#removes unmatched files from fixes folder
foreach($filename in $sourceNoShortcutList){
$fPath = Join-Path "C:\Users\yo\Documents\Powershell Lab\fixes" $fileName
Remove-Item -LiteralPath $fPath
}
foreach($filename in $reqshortcutlist){
$shortcutpath = Join-Path "C:\Users\yo\Documents\Powershell Lab\source" $fileName
$pscpath = "powershell.exe -file '$shortcutpath'"
$sclocation = "C:\Users\yo\Documents\Powershell Lab\fixes\$filename.lnk"
$WScriptObj = New-Object -ComObject ("WScript.Shell")
$shortcut = $WscriptObj.CreateShortcut($sclocation)
$shortcut.TargetPath = $pscpath
$shortcut.Save()
}
跟
$pscpath = "powershell.exe -file '$shortcutpath'"
输出如下所示
powershell.exe -file 'C:\Users\yo\Documents\Powershell Lab\source\find.ps1'
交换 “ 和 ' 如下所示
powershell.exe -file "$shortcutpath"
查看脚本,我手动制作了快捷方式,它们看起来像这样
powershell.exe -file "C:\Users\yo\Documents\Powershell Lab\source\find.ps1"
非常接近
powershell.exe -file 'C:\Users\yo\Documents\Powershell Lab\source\find.ps1'
我相信我需要以某种方式使用“ $shortcutpath 但这样做会引用名称而不是值,但这可能是错误的
我在运行完整脚本时收到的错误如下所示
Value does not fall within the expected range.
At C:\Users\yo\Documents\Powershell Lab\Scripts\scmaker\scriptshortcutmaker.ps1:23 char:1
+ $shortcut.TargetPath = $pscpath
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException
所有详细信息都列在帖子中
答:
0赞
MikeM
10/28/2022
#1
应该是不带参数的文件路径。若要传递参数,请使用该属性。TargetPath
Arguments
如果双引号使用反引号字符或双引号转义,则可以在双引号字符串内使用双引号。
$shortcut.TargetPath = "powershell.exe"
$shortcut.Arguments = "-File ""$shortcutpath"""
评论
0赞
Get-Help
11/1/2022
非常感谢迈克!我已经研究了一段时间,并且已经达到了“powershell.exe -file”“文件路径”,“powershell.exe -file”周围的引号由于末尾的 -file 而导致问题,从来没有想过是否将其放在快捷方式路径之前!谢谢你的帮助,没有它,我永远不会到达那里!
评论
$pscpath = "powershell.exe -file ""$shortcutpath"""