繁体   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