PowerShell “an error occurred while creating the p

2019-03-04 17:15发布

问题:

When attempting to use any of the #Requires commands, for example:

#Requires -Version 3.0 

They error with the text:

An error occurred while creating the pipeline. + CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException + FullyQualifiedErrorId : RuntimeException

I've tested this on ISE and the Console with the same results, my versions are below:

Name                           Value
----                           -----
PSVersion                      5.1.14409.1012
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14409.1012
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

回答1:

$versionMinimum = [Version]'5.0'

if ($versionMinimum -gt $PSVersionTable.PSVersion) { 
    throw "You need Powershell Version $versionMinimum to run this script" 
}


回答2:

My final test before posting the question provided the answer:

It seems the '#Requires' commands are designed to break out of the script if it doesn't meet the requirements rather than posting an error, and testing it on a single line will result in an error.

To test, find your PowerShell version (e.g. 5.1) and save the following transposing 5.1 with your (major.minor) version:

#Requires -version 5.1
$PSVersionTable.PSVersion
Read-Host

This will work on both ISE and the Console, providing an output even if 'Run with PowerShell'.

  • Using the #Requires -(anything) line on its own will display the error.
    • In ISE 'Run selection' will work, as long as it's accompanied by another line of code.
  • Using ISE, If the #Requires parameter doesn't match yours, it'll throw a more descriptive error. If run in the console, it'll break and close.