【问题标题】:Script runs with ISE but not via PowerShell console脚本使用 ISE 运行,但不通过 PowerShell 控制台运行
【发布时间】:2022-02-01 18:46:45
【问题描述】:

我有一个脚本可以在 ISE 上顺利运行,但在通过 PowerShell 控制台运行时会停止。引发的错误:

您不能在空值表达式上调用方法

所以这里是代码示例(不能全部显示):

$global:mainForm.Text= $global:mainForm.text.substring(0,$global:mainFormTitleSize)+" || Save File Name = ..."+$outputFileName.substring($outputFileName.length - $decalage,$decalage)

我使用调试运行 ISE 来检查每个变量,并且所有内容都不为空。 但是当我通过 PowerShell 控制台执行时,$global:mainForm.Text 属性为空。即使它被设置在上面几行并且从未在两者之间触及。

编辑: 经过更多的挖掘,我注意到mainForm 没有声明为$global:,而只是作为一个简单的变量。

这可能是问题的一部分吗? (我对 ps 很陌生,这不是我的脚本,所以我不知道会发生什么)

编辑: (01/02/2022) 我想有一点,我将 PowerShell 设置为打开 .ps1 文件的默认程序。 从那以后,我在上下文菜单中看不到“使用 PowerShell 运行”选项,我只能单击“打开”或“打开方式”,然后单击“Windows PowerShell”。

所以,当我单击“打开”时,我收到了上面描述的错误。 当我单击“使用 Windows PowerShell 打开”时,出现了一组全新的错误。所以还是不行。

现在我有了将默认程序设置回记事本的想法。 “使用 PowerShell 运行”功能恢复正常。 “使用 Windows PowerShell 打开”出现错误。

我不明白。

【问题讨论】:

  • ISE 本身也运行 Powershell。澄清一下,我假设您指的是 Powershell 控制台(出现问题的“地方”)?
  • @EduardUta,第一种情况:右键单击 > 使用 PowerShell 运行 => 错误 // 第二种情况:右键单击 > 编辑(打开 ISE)> 使用 ISE 运行 => 一切正常。

标签: powershell powershell-ise


【解决方案1】:

都灵,

ISE 会自动加载一些Shell 不会自动加载的程序集。 我在所有使用表单的代码中都包含以下代码,以确保无论在何处运行它都能正常工作。

Add-Type -AssemblyName "System.Windows.Forms"

If ($host.Name -eq 'ConsoleHost' -or
    $host.Name -eq 'Visual Studio Code Host') {

  try{  <#+------------------------------------------------+
          | Check that the proper assemblies are loaded    |
          | for using XAML forms.                          |
          | Required for PS Console and Visual Code, while |
          | only Systems.Windows.Forms needed for PSISE!   |
          +------------------------------------------------+
        #>
    $ATArgs = @{AssemblyName = "PresentationCore",
                               "PresentationFramework",
                               "WindowsBase"
                ErrorAction = 'Stop'}
    Add-Type @ATArgs
  } 
  catch {
    $Message = 
        "Failed to load Windows Presentation Framework" +
        " and/or other assemblies required for this program!"
     & $TermMsg
    Exit 
  }
  
} #End If ($host...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-04
    • 2016-04-04
    • 1970-01-01
    相关资源
    最近更新 更多