PowerShell: Использовать короткий формат пути для файлов

В одной из своих ранних статей я вроде как поборол проблему перезапуска скрипта с повышением привилегий до уровня администратора. Скрипт работал, если его запускать из консоли PowerShell, но мне нужно было запускать его несколько более сложным способом:

powershell.exe -ExecutionPolicy Bypass -command "& 'C:\Program Files (x86)\MyUtils\TestRunAs.ps1' 'text with spaces.txt'"

И вот здесь я получил ещё одну ошибку:

x86 : The term 'x86' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the s
pelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:22
+ & {C:\Program Files (x86)\MyUtils\TestRunAs.ps1 -Stop:$False -DeleteT ...
+ ~~~
+ CategoryInfo : ObjectNotFound: (x86:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException

Длинный путь требовал упаковки в двойные кавычки, но я так и не смог победить его при повторном вызове скрипта. В итоге я решил использовать конвертацию длинного пути в формат короткого пути.
Для этого пришлось добавить пару-тройку строк (можно их ещё сократить, но тогда станет сложнее читать код):

  $obj = New-Object -ComObject Scripting.FileSystemObject
  $fullPath = $MyInvocation.MyCommand.Path
  $filePath = $obj.GetFile($fullPath)
  $shortPath = $filePath.ShortPath

Финальный код теперь такой:

param (
  [switch]$DeleteTask,
  [switch]$Stop,
  [switch]$Install,
  [switch]$Uninstall,
  [string]$Parameter = ""
)

Write-Output "Parameter1 = $Parameter"
# Check if script is running as Adminstrator and if not use RunAs
Write-Output "Checking if the script is running as Administrator"
$IsAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")
if (-not $IsAdmin)
{
  Write-Output "The script is NOT running as Administrator, restarting PowerShell as Administrator..."

  $obj = New-Object -ComObject Scripting.FileSystemObject
  $fullPath = $MyInvocation.MyCommand.Path
  $filePath = $obj.GetFile($fullPath)
  $shortPath = $filePath.ShortPath

  $cmd = $shortPath + " -Stop:`$$Stop -DeleteTask:`$$DeleteTask -Install:`$$Install -Uninstall:`$$Uninstall -Parameter `'$Parameter`'"
  $arguments = "-NoProfile -NoExit -Command ""& {$cmd} """
  Start-Process "$psHome\powershell.exe" -Verb Runas -ArgumentList $arguments -ErrorAction 'stop'
  Exit
}
Write-Output "The script is running as Administrator"

Write-Output "DeleteTask = $DeleteTask"
Write-Output "Stop = $Stop"
Write-Output "Install = $Install"
Write-Output "Parameter = $Parameter"

Read-Host "Press <Enter> to exit..."


Подписаться
Уведомление о
guest
0 Комментарий
Inline Feedbacks
View all comments