PowerShell Module and Function Creation: Function not recognized and cannot be called.

Asked 2 years ago, Updated 2 years ago, 75 views

I'm learning how to batch with PowerShell. I'm having trouble with the following symptoms.

The main .ps1 is written as follows.

#Import
Import-Module "$($PSScriptRoot)\Module"

In the Module folder, we put Module.psm1 and wrote the following functions.

Function that works (Imitates the English version of SO)

#Invoke command specifying command path and arguments.
Function Invoke-Command ($commandPath, $commandArguments)
{
  Try{
    $pinfo=New-Object System.Diagnostics.ProcessStartInfo
    $pinfo.FileName=$commandPath
    $pinfo.RedirectStandardError=$true
    $pinfo.RedirectStandardOutput=$true
    $pinfo.UseShellExecute=$false
    $pinfo.Arguments=$commandArguments
    $p = New-Object System.Diagnostics.Process
    $p.StartInfo=$pinfo
    $p.Start() | Out-Null
    $p. WaitForExit()
    [psscustomobject]@{
        StdOut=$p.StandardOutput.ReadToEnd()
        StdErr=$p.StandardError.ReadToEnd()
        ExitCode = $p. ExitCode
    }
  }
  Catch{
     exit
  }
}

I use it like this (excerpts from the relevant parts only)

#Saxon path (modified by execution environment)
$saxon_path='D:\My_Documents/Java/SaxonPE10-6J/saxon-pe-10.6.jar'

# Java path (modified by execution environment)
$java_path='C:/PROGRA~1/Java/jre1.8.0_261/bin'
$java_exec = $java_path+'/'+'java.exe'
# ...
# Java command option & Saxon option/parameter
$java_option='-Xmx1024m'
$java_cmd_option=$java_option+"-jar"+$saxon_path+'-xsl:'+$xsl_path+'-it:'+$initial_template+'-o:'+$out_bind_xml_path+'PRM_XML_PATH='+$data_xml_path

Write-Host "Start generating bind xml file from directory: '$data_xml_path' to file: '$out_bind_xml_path' - ForegroundColor Cyan-BackgroundColor Black;

$start_date_time = Get-Date

$ret = Invoke-Command-commandPath $java_exec-commandArguments $java_cmd_option 
Write-Host $ret.StdOut
Write-Host $ret.StdErrr
Write-Host 'XSLT processing return code: '$ret.ExitCode-ForegroundColor Cyan-BackgroundColor Black

Operational logs (only where applicable)

Start generating bind xml file from directory: 'D:/My_Documents/XML 2020/XXXX/docs/20211104-xml-php-data/xml-xxxx-2021-08-yy-zz' to file: 'C:/Users/toshi/AppData/Local/Temp/214'tmpA'
XSLT processing return code: 0
Processing takes 0 minutes 2 seconds.

Function that won't work (this is also an imitation of the English version of SO)

Function Invoke-Executable{
  # from https://stackoverflow.com/a/24371479/52277
  # Runs the specified executable and captures its exit code, stdout
  # and stderr.
  # Returns—custom object.
  # from http://www.codeducky.org/process-handling-net/ added timeout, using tasks
  CmdletBinding()
  param(
          Parameter (Mandatory=$true)
          ValidateNotNullOrEmpty()
          [String] $commandPath,
          Parameter (Mandatory=$false)
          [String] $commandArguments,
#          Parameter (Mandatory=$false)
#          [String]$sVerb,
          Parameter (Mandatory=$false)
          [Int]$TimeoutMillisconds=1800000#30min
      )
#     Write-Host $commandPath $commandArguments
  
  # Setting process invocation parameters.
  $oPsi = New-Object-TypeName System.Diagnostics.ProcessStartInfo
  $oPsi.CreateNoWindow=$true
  $oPsi.UseShellExecute=$false
  $oPsi.RedirectStandardOutput=$true
  $oPsi.RedirectStandardError=$true
  $oPsi.FileName=$commandPath
  if(![String]::IsNullOrEmpty($commandArguments)){
      $oPsi.Arguments=$commandArguments
  }
#  if(![String]::IsNullOrEmpty($sVerb)){
#      $oPsi.Verb = $sVerb
#  }
  
  # Creating process object.
  $oProcess=New-Object-TypeName System.Diagnostics.Process
  $oProcess.StartInfo=$oPsi

  # Starting process.
  Void $oProcess.Start()
  # Tasks used based on http://www.codeducky.org/process-handling-net/ 
  $outTask=$oProcess.StandardOutput.ReadToEndAsync();
  $errTask = $oProcess.StandardError.ReadToEndAsync();
  $bRet=$oProcess.WaitForExit ($TimeoutMillisconds)
  if (-Not $bRet)
  {
    $oProcess.Kill();
  #  row [System.TimeoutException] ($commandPath + "wasked due to timeout after" + ($TimeoutMilliseconds/1000) + "sec") 
  }
  $outText=$outTask.Result;
  $errText=$errTask.Result;
  if (-Not $bRet)
  {
      $errText = $errText + ($commandPath + "wasked due to timeout after" + ($TimeoutMilliseconds/1000) + "sec") 
  }
  $oResult = New-Object-TypeName PSObject-Property ([ordered])@{
#      "commandPath" = $commandPath;
#      "Args" = $cArgs-join";
      "ExitCode" = $oProcess.ExitCode;
      "StdOut" = $outText;
      "StdErr" = $errText
  })

  return$oResult
}

This function will result in the following error in VSCode's PowerShell.

Start generating DITA topic path: 'C:/Users/toshi/AppData/Local/Temp/e5a353ac-226e-4765-b23d-5d1e2bade516/topic'
Invoke-Executable: D:\My_Documents\XML2020\XXXXXX\docs\xml-php\build-tmc-xml-to-dita.ps1:129:8
Line|
 129 | $ret = Invoke-Executable-commandPath $java_exec-commandArguments$j...
     |         ~~~~~~~~~~~~~~~~~
     | The term 'Invoke-Executable' is not recognized as a name of a cmdlet, function, script file, or executable program.Check the spelling of the name, or if a path was included, verify that the path is correct
     | and try again.

This error has been detected in the following call statements.

#Saxon path, Java path is the same as above.

# Java command option & Saxon option/parameter
$java_option='-Xmx1024m'  
$java_cmd_option=$java_option+"-jar"+$saxon_path+'-t-xsl:'+$xsl_path+'-s:'+$out_map_path+'-o:'+$out_xml_path+'-ea:on'+'PRM_BIND_XML_URL='+$bind_xml_out_outRUTMURL='+PRURL

Write-Host "Start generating DITA topic path: '$out_topic_dir' - ForegroundColor Cyan-BackgroundColor Black;
$start_date_time3 = Get-Date

$ret = Invoke-Executable-commandPath $java_exec-commandArguments $java_cmd_option 

Write-Host $ret.StdOut
Write-Host $ret.StdErrr
Write-Host 'XSLT processing return code: '$ret.ExitCode-ForegroundColor Cyan-BackgroundColor Black

Anyway, it's my first time making modules and functions, so I don't know what to do.
Please let me know if you know the cause.

VSCode PowerShell PSVersionTable information is as follows.

PSD:\My_Documents\XML2020\XXXXXX\docs\xml-php>$PSVersionTable

Name Value
----                           -----
PSVersion 7.2.1
PSEdition Core
GitCommitId 7.2.1
OS Microsoft Windows 10.0.22000
Platform Win32NT
PSCompatibleVersion {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0

powershell

2022-09-29 22:11

1 Answers

I'm very sorry. I solved myself.
It seems that the previous VSCode settings (?) remained in the folder and affected it. When I deleted the folder ".ionide", it worked without any problems.


2022-09-29 22:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.