脚本在ISE中运行,但在Powershell中不运行

时间:2018-05-05 19:07:42

标签: powershell

我有powershell script。如果我在Powershell ISE中打开它,这个脚本运行得很好,但是,如果我右键单击该文件并单击'运行PowerShell'该脚本会抛出错误。

此外,我在之前的主题中读到以下执行模式解决了某些人的问题:

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.Forms

有人说过,我不确定我是否真的可以对此错误做任何事情......我已经加载了System.Drawingpowershell -NoExit -STA -File script.ps1 powershell -NoExit -STA -File script.ps1 -Scope Global ...有没有人知道如何正确执行此文件?

修改

尝试解决问题的其他尝试:

Add-Type -AssemblyName System.Windows.Forms

修改2

我也尝试过添加:

Polynomial

在powershell脚本的顶部。然而,这个问题仍未得到解决。

修改

不确定为什么在

后将其标记为重复
  1. 这个答案已经有了建议的答案和
  2. 推荐的答案说明了为什么会有所不同。
  3. ...

1 个答案:

答案 0 :(得分:1)

正如@PetSerAl在评论中所说,答案在https://stackoverflow.com/a/34637458

  

在执行脚本中的第一个语句之前,会完全解析每个PowerShell脚本。类定义中的不可解析的类型名称标记被视为解析错误。要解决您的问题,您必须在解析类定义之前加载类型,因此类定义必须位于单独的文件中。

最终要解决这个问题,我需要将我的类定义作为单独的文件加载,或者将我的声明存储在头文件中,该头文件调用类定义(以及脚本的其余部分)。

我很惊讶这甚至是一个问题,但它现在有效,所以这很好......

修改

在我的情况下,它与解决方案作者链接的帖子略有不同。我实际上正在构建一个ruby库,用于在Windows机器上执行Powershell。目前我不会将数据写入文件,我无法保证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字符串也能正常工作!

相关问题