Настройка командной строки PowerShell - эквивалент $M$ P$_$+$G в CMD?

StackOverflow https://stackoverflow.com/questions/157923

Вопрос

Я начал "поиграться" с PowerShell и пытаюсь заставить его "вести себя прилично".

Одна из вещей, которые я хотел бы сделать, это настроить приглашение так, чтобы оно было "похоже" на то, что "$ M $ P $ _ $ + $ G" делает в MS-Dos:

Краткое изложение того, что они делают:

Характер| Описание
млндолл . Удаленное имя, связанное с буквой текущего диска, или пустая строка, если текущий диск не является сетевым.
$p Текущий привод и путь
$_ ВВОД-ПЕРЕВОД СТРОКИ
$+ Ноль или более символов со знаком плюс (+) в зависимости от глубины толкать стек каталогов, по одному символу на каждый уровень.
$g > (знак "больше, чем")

Таким образом, конечный результат будет примерно таким:

    \\spma1fp1\JARAVJ$ H:\temp
    ++>

Я смог добавить следующее $M и $_ функциональность (и отличная функция истории) моего запроса выглядит следующим образом:

function prompt
{
   ## Get the history. Since the history may be either empty,
   ## a single item or an array, the @() syntax ensures
   ## that PowerShell treats it as an array
   $history = @(get-history)


   ## If there are any items in the history, find out the
   ## Id of the final one.
   ## PowerShell defaults the $lastId variable to '0' if this
   ## code doesn't execute.
   if($history.Count -gt 0)
   {
      $lastItem = $history[$history.Count - 1]
      $lastId = $lastItem.Id
   }

   ## The command that we're currently entering on the prompt
   ## will be next in the history. Because of that, we'll
   ## take the last history Id and add one to it.
   $nextCommand = $lastId + 1

   ## Get the current location
   $currentDirectory = get-location

   ## Set the Windows Title to  the current location
   $host.ui.RawUI.WindowTitle = "PS: " + $currentDirectory

   ## And create a prompt that shows the command number,
   ## and current location
   "PS:$nextCommand $currentDirectory
>"
}

Но остальное - это еще не то, что мне удалось воспроизвести....

Большое спасибо за советы, которые обязательно придут!

Это было полезно?

Решение

Посмотрите, делает ли это то, что вы хотите:

function prompt
{
   ## Get the history. Since the history may be either empty,
   ## a single item or an array, the @() syntax ensures
   ## that PowerShell treats it as an array
   $history = @(get-history)


   ## If there are any items in the history, find out the
   ## Id of the final one.
   ## PowerShell defaults the $lastId variable to '0' if this
   ## code doesn't execute.
   if($history.Count -gt 0)
   {
      $lastItem = $history[$history.Count - 1]
      $lastId = $lastItem.Id
   }

   ## The command that we're currently entering on the prompt
   ## will be next in the history. Because of that, we'll
   ## take the last history Id and add one to it.
   $nextCommand = $lastId + 1

   ## Get the current location
   $currentDirectory = get-location

   ## Set the Windows Title to  the current location
   $host.ui.RawUI.WindowTitle = "PS: " + $currentDirectory

   ##pushd info
   $pushdCount = $(get-location -stack).count
   $pushPrompt = ""
   for ($i=0; $i -lt $pushdCount; $i++)
   {
       $pushPrompt += "+"
    }

   ## And create a prompt that shows the command number,
   ## and current location
   "PS:$nextCommand $currentDirectory `n$($pushPrompt)>"
}

Другие советы

Это даст вам количество местоположений в стеке pushd:

$(get-location -Stack).count

Благодаря ответу EBGReens, моя "подсказка" теперь способна показывать глубину стека:

 function prompt
 {
    ## Initialize vars
    $depth_string = ""

    ## Get the Stack -Pushd count
    $depth = (get-location -Stack).count

    ## Create a string that has $depth plus signs
    $depth_string = "+" * $depth

    ## Get the history. Since the history may be either empty,
    ## a single item or an array, the @() syntax ensures
    ## that PowerShell treats it as an array
    $history = @(get-history)


    ## If there are any items in the history, find out the
    ## Id of the final one.
    ## PowerShell defaults the $lastId variable to '0' if this
    ## code doesn't execute.
    if($history.Count -gt 0)
    {
       $lastItem = $history[$history.Count - 1]
       $lastId = $lastItem.Id
    }

    ## The command that we're currently entering on the prompt
    ## will be next in the history. Because of that, we'll
    ## take the last history Id and add one to it.
    $nextCommand = $lastId + 1

    ## Get the current location
    $currentDirectory = get-location

    ## Set the Windows Title to  the current location
    $host.ui.RawUI.WindowTitle = "PS: " + $currentDirectory

    ## And create a prompt that shows the command number,
    ## and current location
    "PS:$nextCommand $currentDirectory `n$($depth_string)>"
 }

Следующее даст вам сумму, эквивалентную миллиону долларов.

$mydrive = $pwd.Drive.Name + ":";
$networkShare = (gwmi -class "Win32_MappedLogicalDisk" -filter "DeviceID = '$mydrive'");

if ($networkShare -ne $null)
{
    $networkPath = $networkShare.ProviderName
}

Благодаря советам в:

В PowerShell, как я могу определить, является ли текущий диск подключенным к сети или нет?
В PowerShell, как я могу определить корневой каталог диска (предположим, что это сетевой диск)

Мне удалось заставить это работать.

Мой полный профиль - это:

function prompt
{
   ## Initialize vars
   $depth_string = ""

   ## Get the Stack -Pushd count
   $depth = (get-location -Stack).count

   ## Create a string that has $depth plus signs
   $depth_string = "+" * $depth

   ## Get the history. Since the history may be either empty,
   ## a single item or an array, the @() syntax ensures
   ## that PowerShell treats it as an array
   $history = @(get-history)


   ## If there are any items in the history, find out the
   ## Id of the final one.
   ## PowerShell defaults the $lastId variable to '0' if this
   ## code doesn't execute.
   if($history.Count -gt 0)
   {
      $lastItem = $history[$history.Count - 1]
      $lastId = $lastItem.Id
   }

   ## The command that we're currently entering on the prompt
   ## will be next in the history. Because of that, we'll
   ## take the last history Id and add one to it.
   $nextCommand = $lastId + 1

   ## Get the current location
   $currentDirectory = get-location

   ## Set the Windows Title to  the current location
   $host.ui.RawUI.WindowTitle = "PS: " + $currentDirectory

        ## Get the current location's DRIVE LETTER
        $drive = (get-item ($currentDirectory)).root.name

        ## Make sure we're using a path that is not already UNC
        if ($drive.IndexOf(":") -ne "-1")
            {
                $root_dir = (get-wmiobject Win32_LogicalDisk | ? {$_.deviceid -eq $drive.Trim("\") } | % { $_.providername })+" "
          }
          else
          {
            $root_dir=""
          }


   ## And create a prompt that shows the command number,
   ## and current location
   "PS:$nextCommand $root_dir$currentDirectory `n$($depth_string)>"
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top