簡體   English   中英

腳本在ISE中運行,但不在Powershell中運行

[英]Script runs in ISE but not in Powershell

我有一個powershell腳本 如果我在Powershell ISE中打開該腳本,則該腳本運行完全正常,但是,如果右鍵單擊該文件並單擊“使用powershell運行”,則該腳本會引發錯誤。

此外,我在以前的線程中讀到以下執行模式為某些人解決了該問題:

powershell -STA -File script.ps1

在這種情況下,這不能解決問題,但是確實允許我讀取錯誤:

At C:\Users\sancarn\AppData\Local\Temp\script.ps1:20 char:20
+         $parent = [System.Windows.Forms.TreeNode]$global:database.Ite ...
+                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Windows.Forms.TreeNode].
At C:\Users\sancarn\AppData\Local\Temp\script.ps1:27 char:36
+ ...          [void]$node.nodes.add([System.Windows.Forms.TreeNode]::new(" ...
+                                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Windows.Forms.TreeNode].
At C:\Users\sancarn\AppData\Local\Temp\script.ps1:33 char:45
+ ... PSCustomObject]IWDBGetChildren([System.Windows.Forms.TreeNode]$node)  ...
+                                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Windows.Forms.TreeNode].
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : TypeNotFound

話雖這么說,我不確定我是否真的可以針對此錯誤做任何事情...我已經加載了System.Windows.FormsSystem.Drawing ...是否有人知道如何正確執行此文件?

編輯

其他嘗試解決此問題的嘗試:

powershell -NoExit -STA -File script.ps1
powershell -NoExit -STA -File script.ps1 -Scope Global

編輯2

我也嘗試添加:

Add-Type -AssemblyName System.Windows.Forms

在powershell腳本的頂部。 但是,該問題仍未解決。


編輯:

不知道為什么之后將其標記為重復

  1. 該答案已經有推薦的答案,並且
  2. 推薦的答案說明了為什么這有所不同。

...

正如@PetSerAl在評論中所說,答案在https://stackoverflow.com/a/34637458

在執行腳本中的第一條語句之前,將完全解析每個PowerShell腳本。 類定義中無法解析的類型名稱標記被視為解析錯誤。 為了解決您的問題,您必須在解析類定義之前加載類型,因此類定義必須位於單獨的文件中。

最終,要解決此問題,我需要將類定義作為單獨的文件加載,或將聲明存儲在頭文件中,該頭文件調用類定義(以及腳本的其余部分)。

我很驚訝,這甚至是一個問題,但現在可以使用,所以很好...

編輯

就我而言,它與解決方案作者所鏈接的帖子有些不同。 我實際上是在構建用於在Windows機器上執行Powershell的ruby庫。 目前,我不將數據寫入文件,並且不能保證here-string / invoke-expression可以正常工作。

Invoke-Expression @"
$anotherString=@"
    hello world!
"@    
"@ <--- Powershell will throw an error here!

相反,我決定對標頭進行編碼(如果存在標頭),然后在運行時解碼並執行

require 'base64'
if header!=""
    encoded_body = Base64.strict_encode64(body.encode("utf-16le"))
    body = <<-END_TRANSFORMATION
        #{header}

        $encoded_body = "#{encoded_body}"
        Invoke-Expression $([System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($encoded_body)))
    END_TRANSFORMATION
end

到目前為止,這似乎可以在所有情況下使用,不需要外部文件,即使用戶在Powershell腳本中使用here-doc字符串也可以使用!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM