이 New-Item 명령이 powershell에서는 작동하지만 ps1 스크립트에서는 작동하지 않는 이유는 무엇입니까?

이 New-Item 명령이 powershell에서는 작동하지만 ps1 스크립트에서는 작동하지 않는 이유는 무엇입니까?

여기에 완전히 갇혀서 무엇을 해야할지 모르겠습니다. 원격 컴퓨터에서 빠른 작업을 수행하려고 할 때마다 몇 분의 시간을 절약할 수 있도록 작업을 위해 구성하고 있는 객관식 대화형 Powershell 스크립트가 있습니다.

다른 모든 선택 항목에 대한 코드를 모두 로 대체했기 You have selected #때문에 나머지 스크립트 내용으로 인해 지루해지지는 않지만 선택 항목이 6나를 미치게 만듭니다.

이것이 제가 목표로 하는 것이지만 아직 첫 번째 중요 항목을 통과할 수 없습니다.

  • .vnc파일 만들기
  • 표준 VNC 프로토콜 텍스트 본문을 파일에 추가합니다.
  • $ComputerName뒤에 추가Host=
  • 파일 실행

문제는 아래 파일이 전혀 생성되지 않는다는 것입니다. Powershell에 직접 복사/붙여넣으면 작동하지만 스크립트에서는 실행되지 않습니다! 왜 그럴 수 있는지 아는 사람이 있나요?

$commands = {
  function Show-Menu
  {
    param (
      [string]$Title = 'My Menu'
    )
    Clear-Host
    Write-Host "================ $Title ================"

    Write-Host "1: Press '1' (Description)."
    Write-Host "2: Press '2' (Description)."
    Write-Host "3: Press '3' (Description)."
    Write-Host "4: Press '4' (Description)."
    Write-Host "5: Press '5' (Description)."
    Write-Host "6: Press '6' To start a VNC Connection."
    Write-Host "Q: Press 'Q' to quit."
  }

  Show-Menu –Title 'My Menu'
  $selection = Read-Host "Please make a selection"
  switch ($selection)
  {
    '1' {
      "You have selected 1"
      sleep -seconds 2
    } '2' {
      "You have selected 2"
      sleep -seconds 2
    } '3' {
      "You have selected 3"
      sleep -seconds 2
    } '4' {
      "You have selected 4"
      sleep -seconds 2
    } '5' {
      "You have selected 5"
      sleep -seconds 2
    } '6' {
      $ComputerName = (Read-Host "ComputerName")
      {
        New-Item -Path "C:\Windows\Temp\$ComputerName.VNC"
        Set-Content "C:\Windows\Temp\$ComputerName.VNC" '
        [connection]
        host=$ComputerName
        port=5900
        [options]
        use_encoding_1=1
        copyrect=1
        viewonly=0
        fullscreen=0
        8bit=0
        shared=1
        belldeiconify=0
        disableclipboard=0
        swapmouse=0
        fitwindow=0
        cursorshape=1
        noremotecursor=0
        preferred_encoding=7
        compresslevel=-1
        quality=6
        localcursor=1
        scale_den=1
        scale_num=1
        local_cursor_shape=1'
      }
    } 'q' {
      #Closes the script
      return
    }
  }
  .$commands

}
&$commands

답변1

Powershell에 직접 복사/붙여넣기하면 작동하지만 스크립트에서는 실행되지 않습니다.

이는 부적절한 실행 정책처럼 들립니다. 실행 Get-ExecutionPolicy하여 확인할 수 있습니다. 아마도 Restricted.

이를 영구적으로 변경하려면 관리자 권한 PowerShell을 실행 Set-ExecutionPolicy RemoteSigned하고 y.

스크립트 실행을 위해 일시적으로 변경하려면 다음과 같이 실행할 수 있습니다.

powershell -ExecutionPolicy Bypass -File .\ScriptFile.ps1

따라서 스크립트 파일에서 스크립트를 실행하는 방법은 다음과 같습니다. 그 외에도 이미 언급한 또 다른 문제가 있습니다.@jfrmilner. 여섯 번째 옵션에서는 추가 중괄호로 다른 스크립트 블록을 정의합니다.

...
} '6' {
      $ComputerName = (Read-Host "ComputerName")
      {
        # This just the definition of a scriptblock and will not be executed!
        # Instead, it will be sent to stdout.
      }
    } 'q' {
...

정의 자체는 해당 행을 실행하지 않습니다. 이 문제를 해결할 수 있는 두 가지 방법이 있습니다.

  1. 중괄호를 생략하므로 스크립트 블록을 정의하지 않습니다. 라인이 실행됩니다.
  2. scriptblock 앞에 a를 붙이면 .실행됩니다.
...
} '6' {
      $ComputerName = (Read-Host "ComputerName")
      .{
        # This is a scriptblock that will directly be executed!
      }
    } 'q' {
...

답변2

@Reg Edit와 @Lee-Dailey의 말과 동일합니다.

화면을 볼 수 없습니다.

둘째, 왜 기대하겠어요?

&$commands

...이것이 스크립트에서 작동하나요?

$commands는 실행할 .ps1이 아니며 스크립트의 스크립트 블록입니다.

powershell.exe 콘솔이나 ISE 또는 VSCode에 붙여넣는다고 가정하면 코드를 로드하고 기존 PowerShell 인스턴스에서 실행했으며 해당 인스턴스에서 코드를 읽었기 때문에 작동한다고 가정합니다.

따라서 이 코드가 Commands.ps1로 저장되지 않으면 코드가 실행 중이거나 호출되는 PowerShell 인스턴스에 로드되지 않으므로 &$commands는 문제가 됩니다.

또한 해당 스크립트 블록은 실제로 전혀 필요하지 않습니다.

그럼 이것을 시도해 보세요...

# VNCCommands.ps1
function Show-Menu
{
    param 
    (
        [string]$Title = 'My Menu'
    )

    Clear-Host
    $Banner = '='*16
    "$Banner $Title $Banner"

    "1: Press '1' (Description)."
    "2: Press '2' (Description)."
    "3: Press '3' (Description)."
    "4: Press '4' (Description)."
    "5: Press '5' (Description)."
    "6: Press '6' To start a VNC Connection."
    "Q: Press 'Q' to quit."
}

Show-Menu –Title 'My Menu'
$selection = Read-Host "Please make a selection"

switch ($selection)
{
    1 
    {
        "You have selected 1"
        sleep -seconds 2
    } 
    2 
    {
        "You have selected 2"
        sleep -seconds 2
    } 
    3 
    {
        "You have selected 3"
        sleep -seconds 2
    } 
    4 
    {
        "You have selected 4"
        sleep -seconds 2
    } 
    5 
    {
        "You have selected 5"
        sleep -seconds 2
    } 
    6 
    {
        $ComputerName = Read-Host -Prompt 'Enter a computer name: '
        If (-Not (Test-Path -Path "D:\temp\$ComputerName"))
        {New-Item -Path 'D:\Temp' -Name "$ComputerName.VNC" -ItemType File -Verbose}
        Else {Write-Warning -Message "D:\temp\$ComputerName.VNC creation failed"}
    } 
    'q' {return}
}

실행하다 ---

.\VNCCommands.ps1



# Results
<#
================ My Menu ================
1: Press '1' (Description).
2: Press '2' (Description).
3: Press '3' (Description).
4: Press '4' (Description).
5: Press '5' (Description).
6: Press '6' To start a VNC Connection.
Q: Press 'Q' to quit.
Please make a selection: 6
Enter a computer name: : test
VERBOSE: Performing the operation "Create File" on target "Destination: D:\Temp\test.VNC".


    Directory: D:\Temp


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----         19-Jul-20     17:14              0 test.VNC
#>

관련 정보