PowerShell에서 별칭을 동적으로 생성

PowerShell에서 별칭을 동적으로 생성

일부 별칭을 동적으로 생성하고 싶지만 코드가 작동하지 않습니다. 코드는 다음과 같습니다.

# Drives
$drives = ("a","b","c","d","e")
foreach ($drive in $drives) {
    New-Item -Path alias:\ -Name $drive -Value GoToDrive($drive) #.GetNewClosure()
}

function GoToDrive($drive) {
    $formatted = "$($drive):\"
    if (Test-Path $formatted) {
        Set-Location $formatted
    } else {
        Write-Host "`"$formatted`" does not exist."
    }
}

"a", "b" 또는 $drives의 문자 중 하나를 입력하면 작업 디렉터리가 해당 드라이브 문자(예: A:)로 변경됩니다.

지금 내가 받고 있는 오류는 다음과 같습니다.

New-Item : A positional parameter cannot be found that accepts argument 'a'.
At C:\Users\prubi\OneDrive\Documentos\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:17 char:5
+     New-Item -Path alias:\ -Name $drive -Value GoToDrive($drive) #.Ge ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [New-Item], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewItemCommand

New-Item : A positional parameter cannot be found that accepts argument 'b'.
At C:\Users\prubi\OneDrive\Documentos\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:17 char:5
+     New-Item -Path alias:\ -Name $drive -Value GoToDrive($drive) #.Ge ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [New-Item], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewItemCommand

New-Item : A positional parameter cannot be found that accepts argument 'c'.
At C:\Users\prubi\OneDrive\Documentos\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:17 char:5
+     New-Item -Path alias:\ -Name $drive -Value GoToDrive($drive) #.Ge ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [New-Item], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewItemCommand

New-Item : A positional parameter cannot be found that accepts argument 'd'.
At C:\Users\prubi\OneDrive\Documentos\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:17 char:5
+     New-Item -Path alias:\ -Name $drive -Value GoToDrive($drive) #.Ge ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [New-Item], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewItemCommand

New-Item : A positional parameter cannot be found that accepts argument 'e'.
At C:\Users\prubi\OneDrive\Documentos\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:17 char:5
+     New-Item -Path alias:\ -Name $drive -Value GoToDrive($drive) #.Ge ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [New-Item], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.NewItemCommand

누구든지 내가 이 일을 할 수 있도록 도와줄 수 있나요?

답변1

즉각적인 문제는 PowerShell이 -Value GoToDrive($drive)​​스위치 -Value 'GoToDrive'와 위치 매개 변수를 지정하는 것으로 해석한다는 것입니다 $drive. (이것은 이상하고 직관적이지 않습니다. 그렇습니다.) GoToDrive($drive)괄호로 묶으면 아직 존재하지 않는 GoToDrive함수를 호출한 다음 결과를 에 대한 인수로 사용하려고 시도합니다. 이는 이전에 정의된 -Value경우에도 원하는 것이 아닙니다 . GoToDrive또 다른 문제는 별칭이 호출하는 명령에 인수를 제공할 수 없다는 것입니다. 이는 명령의 대체 이름일 뿐입니다.

바로가기 기능을 생성하는 명령을 동적으로 실행해야 합니다.

# This is the exact same GoToDrive function you've been using
function GoToDrive($drive) {
    $formatted = "$($drive):\"
    if (Test-Path $formatted) {
        Set-Location $formatted
    } else {
        Write-Host "`"$formatted`" does not exist."
    }
}

# This does the magic
'a', 'b', 'c', 'd', 'e' | % {iex "function $_ {GoToDrive '$_'}"}

Invoke-Expression, iex간단히 말해서 명령줄에 직접 입력한 것처럼 런타임에 결정된 인수를 실행합니다. 따라서 마지막 줄은 , function a {GoToDrive 'a'}그런 function b {GoToDrive 'b'}다음 등을 실행합니다.

관련 정보