ค้นหาเว็บไซต์

โปรไฟล์เวอร์ชัน PowerShell


โดยพื้นฐานแล้ว สคริปต์โปรไฟล์ของฉันจะตรวจสอบเวอร์ชันก่อนก่อนที่จะทำอะไรก็ตาม คุณสามารถใช้ตัวแปร $psversiontable


PS C:\> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      3.0
WSManStackVersion              3.0
SerializationVersion           1.1.0.1
CLRVersion                     4.0.30319.18033
BuildVersion                   6.2.9200.16434
PSCompatibleVersions           {1.0, 2.0, 3.0}
PSRemotingProtocolVersion      2.2

คุณสมบัติ PSVersion คือสิ่งที่ฉันกำลังมองหา ด้วยข้อมูลนี้ ฉันสามารถรวมสคริปต์โปรไฟล์ PowerShell ของฉันไว้ในคำสั่ง IF แบบธรรมดาได้

#requires -version 2.0

<#
Use code like this in your PowerShell profile if it will
be shared between PowerShell 2 and PowerShell 3 sessions
on the same computer
#>

if ($psversiontable.psversion -eq '3.0') {
 Write-Host "You are running PowerShell 3.0" -ForegroundColor Green
 #insert 3.0 specific commands
 $PSDefaultParameterValues.Add("Format-Table:Autosize",$True)
}
else {
  Write-Host "You are running PowerShell 2.0" -ForegroundColor Yellow
  #insert 2.0 specific commands
}

#insert commands that apply to both versions

ฉันคิดว่าความคิดเห็นในตัวอย่างโค้ดค่อนข้างชัดเจนและไม่มีอะไรให้เพิ่มเติมมากนัก บรรทัด Write-Host มีไว้สำหรับการทดสอบเท่านั้น คุณไม่ต้องการมันจริงๆ

ตอนนี้ฉันสามารถกำหนดค่าเซสชัน PowerShell ได้อย่างถูกต้องโดยไม่คำนึงถึงเวอร์ชันและไม่มีข้อผิดพลาด

บทความที่เกี่ยวข้อง