การสร้างฟังก์ชัน PowerShell เพิ่มเติม
ในโพสต์ล่าสุด ฉันได้กล่าวถึงกระบวนการที่คุณอาจต้องดำเนินการในการพัฒนาฟังก์ชัน PowerShell ในตอนท้าย ฉันไม่เพียงมีเครื่องมือใหม่สำหรับกล่องเครื่องมือ PowerShell ของฉันเท่านั้น แต่ฉันยังมีโครงร่างฟังก์ชันที่สามารถนำมาใช้ซ้ำได้อีกด้วย หากคุณอ่านบทความก่อนหน้านี้ คุณควรรู้จักแนวคิดเรื่อง "การจัดการในวงกว้าง" หากเป็นไปได้ ฉันต้องการให้ฟังก์ชันของฉันใช้งานได้ ไม่ใช่เพื่อสิ่งเดียวหรือกับคอมพิวเตอร์หลายๆ คน วิธีหนึ่งในการบรรลุเป้าหมายนั้นคือการรวมเอาระยะไกลเข้าด้วยกัน เครื่องมือหน่วยความจำกระบวนการที่ฉันสร้างขึ้นใช้ Invoke-Command เพื่อเรียกใช้นิพจน์ PowerShell แบบง่ายโดยใช้ Get-Process เพื่อดึงข้อมูลที่ฉันต้องการ ฉันสามารถนำเทคนิคนั้นกลับมาใช้ซ้ำเพื่อทำงานทุกประเภทให้สำเร็จได้ มาทำอย่างอื่นกัน
เมื่อใดก็ตามที่คุณกำลังสร้างสคริปต์หรือฟังก์ชัน PowerShell ฉันขอย้ำว่าคุณควรเริ่มต้นด้วยคำสั่งหรือชุดคำสั่งที่คุณสามารถเรียกใช้จากคอนโซลได้ นี่จะเป็นแกนหลักของสคริปต์หรือฟังก์ชัน สคริปต์ของคุณส่วนใหญ่เพิ่มความสะดวก การจัดการข้อผิดพลาด และการปรับปรุงอื่นๆ รอบแกนกลางนี้ สำหรับฟังก์ชันถัดไปของฉัน ฉันต้องการจำลองข้อมูลที่แสดงเมื่อคุณรันคำสั่ง winver.exe หากต้องการดูตัวเองให้รัน winver เมื่อได้รับแจ้งหรือในกล่อง Run
ข้อมูลที่แสดงส่วนใหญ่สามารถเรียกค้นได้โดยการสอบถามคลาส Win32_OperatingSystem โดยใช้ Get-CimInstance ฉันถือว่า Get-WmiObject เลิกใช้แล้วและไม่ค่อยได้ใช้ตอนนี้ อย่างไรก็ตาม ฉันรู้ด้วยว่าข้อมูลเดียวกันนี้สามารถพบได้ในรีจิสทรี ดังนั้นเพื่อการเปลี่ยนแปลงฉันจึงตัดสินใจสอบถามรีจิสทรีเพื่อรับข้อมูลเดียวกันและลงเอยด้วยรหัสนี้
$RegPath = 'HKLM:\SOFTWARE\Microsoft\Windows nt\CurrentVersion\'
Get-ItemProperty -Path $RegPath | Select-Object -Property ProductName, EditionID, ReleaseID,
@{Name = "Build"; Expression = {"$($_.CurrentBuild).$($_.UBR)"}},
@{Name = "InstalledUTC"; Expression = { ([datetime]"1/1/1601").AddTicks($_.InstallTime) }},
@{Name = "Computername"; Expression = {$env:computername}}
ฉันมักจะคิดที่จะเขียนออบเจ็กต์ลงในไปป์ไลน์ ดังนั้นฉันจึงกำหนดคุณสมบัติแบบกำหนดเองบางอย่างที่ไม่เพียงแต่จำลองสิ่งที่ฉันเห็นใน winver เท่านั้น แต่ยังอาจมีประโยชน์อีกด้วย
ตอนนี้ฉันมีโค้ดที่ใช้งานได้แล้ว ฉันสามารถเสียบโค้ดนี้เข้ากับ scriptblock สำหรับฟังก์ชันของฉันได้ จริงๆแล้วขอย้อนกลับไปก่อน
ฟังก์ชัน Get-ProcessMemory ที่ฉันเขียนในตอนท้ายกลายเป็นโมเดลที่ยอดเยี่ยมที่ฉันสามารถนำกลับมาใช้ใหม่ได้ ดังนั้นฉันจึงสร้างไฟล์เวอร์ชันเทมเพลต คุณสามารถรับเทมเพลตได้จาก GitHub
Get-Something.ps1:
Function Get-Something {
<#
.SYNOPSIS
Get something
.DESCRIPTION
Describe what this does.
Many of the parameters are the same as in Invoke-Command.
.PARAMETER Computername
Specifies the computers on which the command runs. The default is the local computer.
When you use the ComputerName parameter, Windows PowerShell creates a temporary connection that is used only to run the specified command and is then closed. If you need a persistent connection, use the Session parameter.
Type the NETBIOS name, IP address, or fully qualified domain name of one or more computers in a comma-separated list. To specify the local computer, type the computer name, localhost, or a dot (.).
To use an IP address in the value of ComputerName , the command must include the Credential parameter. Also, the computer must be configured for HTTPS transport or the IP address of the remote computer must be included in the WinRM TrustedHosts list on the local computer. For instructions for adding a computer name to the TrustedHosts list, see "How to Add a Computer to the Trusted Host List" in about_Remote_Troubleshooting.
On Windows Vista and later versions of the Windows operating system, to include the local computer in the value of ComputerName , you must open Windows PowerShell by using the Run as administrator option.
.PARAMETER Credential
Specifies a user account that has permission to perform this action. The default is the current user.
Type a user name, such as User01 or Domain01\User01. Or, enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, this cmdlet prompts you for a password.
.PARAMETER UseSSL
Indicates that this cmdlet uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer. By default, SSL is not used.
WS-Management encrypts all Windows PowerShell content transmitted over the network. The UseSSL parameter is an additional protection that sends the data across an HTTPS, instead of HTTP.
If you use this parameter, but SSL is not available on the port that is used for the command, the command fails.
.PARAMETER ThrottleLimit
Specifies the maximum number of concurrent connections that can be established to run this command. If you omit this parameter or enter a value of 0, the default value, 32, is used.
The throttle limit applies only to the current command, not to the session or to the computer.
.PARAMETER Authentication
Specifies the mechanism that is used to authenticate the user's credentials. The acceptable values for this
parameter are:
- Default
- Basic
- Credssp
- Digest
- Kerberos
- Negotiate
- NegotiateWithImplicitCredential
The default value is Default.
CredSSP authentication is available only in Windows Vista, Windows Server 2008, and later versions of the Windows operating system.
For information about the values of this parameter, see the description of the AuthenticationMechanismEnumeration (http://go.microsoft.com/fwlink/?LinkID=144382) in theMicrosoft Developer Network (MSDN) library.
CAUTION: Credential Security Support Provider (CredSSP) authentication, in which the user's credentials are passed to a remote computer to be authenticated, is designed for commands that require authentication on more than one resource, such as accessing a remote network share. This mechanism increases the security risk of the remote operation. If the remote computer is compromised, the credentials that are passed to it can be used to control the
network session.
.EXAMPLE
PS C:\> Get-Something
.INPUTS
System.String
.OUTPUTS
Custom object
.NOTES
Learn more about PowerShell: http://jdhitsolutions.com/blog/essential-powershell-resources/
.LINK
Invoke-Command
#>
[cmdletbinding()]
[OutputType("custom object")]
[alias('wver')]
Param (
[Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName,Position = 0)]
[ValidateNotNullOrEmpty()]
[string[]]$Computername = $env:COMPUTERNAME,
[PSCredential]$Credential,
[switch]$UseSSL,
[Int32]$ThrottleLimit,
[ValidateSet('Default', 'Basic', 'Credssp', 'Digest', 'Kerberos', 'Negotiate', 'NegotiateWithImplicitCredential')]
[ValidateNotNullorEmpty()]
[string]$Authentication = "default"
)
Begin {
Write-Verbose "Starting $($MyInvocation.Mycommand)"
$sb = {
#add your code
#you can pass local variables with $using or define scriptblock parameters and pass arguments
} #close scriptblock
#update PSBoundParameters so it can be splatted to Invoke-Command
$PSBoundParameters.Add("ScriptBlock", $sb) | Out-Null
$PSBoundParameters.Add("HideComputername", $True) | Out-Null
} #begin
Process {
if (-Not $PSBoundParameters.ContainsKey("Computername")) {
#add the default value if nothing was specified
$PSBoundParameters.Add("Computername", $Computername) | Out-Null
}
$PSBoundParameters | Out-String | Write-Verbose
Invoke-Command @PSBoundParameters | Select-Object -Property * -ExcludeProperty RunspaceID, PS*
} #process
End {
Write-Verbose "Ending $($MyInvocation.Mycommand)"
} #end
} #close function
<#
json powershell snippet for VSCode
"get-something": {
"prefix": "get-something",
"body": [
"\r",
"Function Get-Something {\r",
"<#\r",
".SYNOPSIS\r",
"Get ...\r",
".DESCRIPTION\r",
"Describe what this does.\r",
"\r",
"Many of the parameters are the same as in Invoke-Command.\r",
".PARAMETER Computername\r",
"Specifies the computers on which the command runs. The default is the local computer.\r",
"\r",
"When you use the ComputerName parameter, Windows PowerShell creates a temporary connection that is used only to run the specified command and is then closed. If you need a persistent connection, use the Session parameter.\r",
"\r",
"Type the NETBIOS name, IP address, or fully qualified domain name of one or more computers in a comma-separated list. To specify the local computer, type the computer name, localhost, or a dot (.).\r",
"\r",
"To use an IP address in the value of ComputerName , the command must include the Credential parameter. Also, the computer must be configured for HTTPS transport or the IP address of the remote computer must be included in the WinRM TrustedHosts list on the local computer. For instructions for adding a computer name to the TrustedHosts list, see \"How to Add a Computer to the Trusted Host List\" in about_Remote_Troubleshooting.\r",
"\r",
"On Windows Vista and later versions of the Windows operating system, to include the local computer in the value of ComputerName , you must open Windows PowerShell by using the Run as administrator option.\r",
".PARAMETER Credential\r",
"Specifies a user account that has permission to perform this action. The default is the current user.\r",
"\r",
"Type a user name, such as User01 or Domain01\\User01. Or, enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, this cmdlet prompts you for a password.\r",
".PARAMETER UseSSL\r",
"Indicates that this cmdlet uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer. By default, SSL is not used.\r",
"\r",
"WS-Management encrypts all Windows PowerShell content transmitted over the network. The UseSSL parameter is an additional protection that sends the data across an HTTPS, instead of HTTP.\r",
"\r",
"If you use this parameter, but SSL is not available on the port that is used for the command, the command fails.\r",
".PARAMETER ThrottleLimit\r",
"Specifies the maximum number of concurrent connections that can be established to run this command. If you omit this parameter or enter a value of 0, the default value, 32, is used.\r",
"\r",
"The throttle limit applies only to the current command, not to the session or to the computer.\r",
".PARAMETER Authentication\r",
"Specifies the mechanism that is used to authenticate the user's credentials. The acceptable values for this\r",
"parameter are:\r",
"\r",
"- Default\r",
"- Basic\r",
"- Credssp\r",
"- Digest\r",
"- Kerberos\r",
"- Negotiate\r",
"- NegotiateWithImplicitCredential\r",
"\r",
"The default value is Default.\r",
"\r",
"CredSSP authentication is available only in Windows Vista, Windows Server 2008, and later versions of the Windows operating system.\r",
"\r",
"For information about the values of this parameter, see the description of the AuthenticationMechanismEnumeration (http://go.microsoft.com/fwlink/?LinkID=144382) in theMicrosoft Developer Network (MSDN) library.\r",
"\r",
"CAUTION: Credential Security Support Provider (CredSSP) authentication, in which the user's credentials are passed to a remote computer to be authenticated, is designed for commands that require authentication on more than one resource, such as accessing a remote network share. This mechanism increases the security risk of the remote operation. If the remote computer is compromised, the credentials that are passed to it can be used to control the\r",
"network session.\r",
".EXAMPLE\r",
"PS C:\\> Get-Something\r",
"\r",
".INPUTS\r",
"System.String\r",
".OUTPUTS\r",
"Custom object\r",
".NOTES\r",
"Learn more about PowerShell: http://jdhitsolutions.com/blog/essential-powershell-resources/\r",
".LINK\r",
"Invoke-Command\r",
"#>\r",
"\r",
" [cmdletbinding()]\r",
" [OutputType(\"custom object\")]\r",
" [alias('wver')]\r",
"\r",
" Param (\r",
" [Parameter(ValueFromPipeline, Position = 0)]\r",
" [ValidateNotNullOrEmpty()]\r",
" [string[]]$$Computername = $$env:COMPUTERNAME,\r",
" [PSCredential]$$Credential,\r",
" [switch]$$UseSSL,\r",
" [Int32]$$ThrottleLimit,\r",
" [ValidateSet('Default', 'Basic', 'Credssp', 'Digest', 'Kerberos', 'Negotiate', 'NegotiateWithImplicitCredential')]\r",
" [ValidateNotNullorEmpty()]\r",
" [string]$$Authentication = \"default\"\r",
" )\r",
"\r",
" Begin {\r",
"\r",
" Write-Verbose \"Starting $($$MyInvocation.Mycommand)\"\r",
"\r",
" $$sb = {\r",
"\r",
" #add your code\r",
" #you can pass local variables with $using or define scriptblock parameters and pass arguments\r",
"\r",
" } #close scriptblock\r",
"\r",
" #update PSBoundParameters so it can be splatted to Invoke-Command\r",
" $$PSBoundParameters.Add(\"ScriptBlock\", $$sb) | Out-Null\r",
" $$PSBoundParameters.Add(\"HideComputername\", $$True) | Out-Null\r",
" } #begin\r",
"\r",
" Process {\r",
" if (-Not $$PSBoundParameters.ContainsKey(\"Computername\")) {\r",
" #add the default value if nothing was specified\r",
" $$PSBoundParameters.Add(\"Computername\", $$Computername) | Out-Null\r",
" }\r",
" $$PSBoundParameters | Out-String | Write-Verbose\r",
" Invoke-Command @PSBoundParameters | Select-Object -Property * -ExcludeProperty RunspaceID, PS*\r",
" } #process\r",
"\r",
" End {\r",
"\r",
" Write-Verbose \"Ending $($$MyInvocation.Mycommand)\"\r",
"\r",
" } #end\r",
"} #close function\r",
""
],
"description": "template for my Get-Something technique"
}
#>ฉันยังเพิ่มความช่วยเหลือตามความคิดเห็นสำหรับพารามิเตอร์ระยะไกลทั้งหมดอีกด้วย ในบล็อก Begin มีส่วนสำหรับกำหนด scriptblock ที่ฉันตั้งใจจะเรียกใช้จากระยะไกล นั่นคือที่ที่ฉันจะติดรหัสที่เกี่ยวข้องกับรีจิสทรีของฉัน ฉันไม่จำเป็นต้องผ่านพารามิเตอร์อื่นใด ถ้าฉันทำฉันจะเพิ่มพวกเขาและอัปเดตความช่วยเหลือ ขั้นตอนสำคัญ ได้แก่ การอัปเดต scriptblock เพื่อรวมค่าเหล่านั้นโดยใช้การอ้างอิง $using: หรือส่งพารามิเตอร์ ArgumentList ไปยัง Invoke-Command เทมเพลตของฉันกำลังแยก PSBoundParameters เป็น Inrigg-Command ดังนั้นฉัน (หรือคุณ) จำเป็นต้องเพิ่มหรือลบพารามิเตอร์ตามนั้น
เมื่อเสร็จแล้ว ฉันมีคำสั่งใหม่ชื่อ Get-WindowsVersion
ตอนนี้ฉันมีเครื่องมือ PowerShell ที่ปรับขนาดได้!
แม้ว่าฉันจะเน้นย้ำถึงความสำคัญของ "วัตถุในไปป์ไลน์ PowerShell" อยู่เสมอ แต่ฉันก็ตระหนักว่าบางครั้งเราต้องการสตริงหรือข้อความบางส่วน เมื่อเรียกใช้ winver.exe นั่นคือสิ่งที่ฉันเห็น แน่นอนว่าเครื่องมือกราฟิกไม่ได้ปรับขนาด แต่ PowerShell สามารถทำได้ ฉันมีข้อมูลทั้งหมดในเอาต์พุตจากฟังก์ชันของฉันเพื่อสร้างสตริงแล้ว ความคิดแรกของฉันคือการเพิ่มพารามิเตอร์ให้กับฟังก์ชัน เช่น -AsString ซึ่งหากใช้ จะเขียนสตริงลงในไปป์ไลน์แทนที่จะเป็นวัตถุ นั่นคงเป็นทางขี้เกียจและฉันก็รู้ตัวผิด
ฟังก์ชัน PowerShell ควรเขียนออบเจ็กต์ประเภทเดียวลงในไปป์ไลน์และฉันอาจสร้างฟังก์ชันที่จะทำอะไร 2 สิ่ง คำตอบคือต้องเขียนฟังก์ชันที่สอง Get-WindowsVersionString นี่จะเขียนได้ง่ายจริงๆ เพราะสิ่งที่ฉันต้องทำคือเรียกใช้ฟังก์ชัน Get-WindowsVersion ของฉันสำหรับคอมพิวเตอร์แต่ละเครื่องและสร้างสตริงจากผลลัพธ์ สิ่งนี้จะกลายเป็น Process scriptblock
Process {
$results = Get-WindowsVersion @PSBoundParameters
#write a version string for each computer
` foreach ($result in $results) {
"{0} Version {1} (OS Build {2})" -f $result.ProductName, $result.releaseID, $result.build
}
} #process
พารามิเตอร์สำหรับฟังก์ชันนี้เหมือนกับ Get-WindowsVersion ดังนั้นสิ่งที่ฉันต้องทำคือ "ส่ง" พวกมันโดยใช้การสลับ คุณสามารถดูโฟลว์ในเอาต์พุตแบบละเอียดของฟังก์ชันได้
ผลลัพธ์ที่ได้คือฉันมี 2 ฟังก์ชันเพื่อให้ได้รับข้อมูลที่ฉันต้องการและอยู่ในรูปแบบที่แตกต่างกันได้อย่างง่ายดาย รหัสสำหรับทั้งสองฟังก์ชั่นก็อยู่บน Github ด้วย
Get-WindowsVersion.ps1:
Function Get-WindowsVersion {
<#
.SYNOPSIS
Get Windows version information
.DESCRIPTION
This is a PowerShell version of the winver.exe utility. This commands uses PowerShell remoting to query the registry on a remote machine to retrieve Windows version information.The parameters are the same as in Invoke-Command.
.PARAMETER Computername
Specifies the computers on which the command runs. The default is the local computer.
When you use the ComputerName parameter, Windows PowerShell creates a temporary connection that is used only to run the specified command and is then closed. If you need a persistent connection, use the Session parameter.
Type the NETBIOS name, IP address, or fully qualified domain name of one or more computers in a comma-separated list. To specify the local computer, type the computer name, localhost, or a dot (.).
To use an IP address in the value of ComputerName , the command must include the Credential parameter. Also, the computer must be configured for HTTPS transport or the IP address of the remote computer must be included in the WinRM TrustedHosts list on the local computer. For instructions for adding a computer name to the TrustedHosts list, see "How to Add a Computer to the Trusted Host List" in about_Remote_Troubleshooting.
On Windows Vista and later versions of the Windows operating system, to include the local computer in the value of ComputerName , you must open Windows PowerShell by using the Run as administrator option.
.PARAMETER Credential
Specifies a user account that has permission to perform this action. The default is the current user.
Type a user name, such as User01 or Domain01\User01. Or, enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, this cmdlet prompts you for a password.
.PARAMETER UseSSL
Indicates that this cmdlet uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer. By default, SSL is not used.
WS-Management encrypts all Windows PowerShell content transmitted over the network. The UseSSL parameter is an additional protection that sends the data across an HTTPS, instead of HTTP.
If you use this parameter, but SSL is not available on the port that is used for the command, the command fails.
.PARAMETER ThrottleLimit
Specifies the maximum number of concurrent connections that can be established to run this command. If you omit this parameter or enter a value of 0, the default value, 32, is used.
The throttle limit applies only to the current command, not to the session or to the computer.
.PARAMETER Authentication
Specifies the mechanism that is used to authenticate the user's credentials. The acceptable values for this
parameter are:
- Default
- Basic
- Credssp
- Digest
- Kerberos
- Negotiate
- NegotiateWithImplicitCredential
The default value is Default.
CredSSP authentication is available only in Windows Vista, Windows Server 2008, and later versions of the Windows operating system.
For information about the values of this parameter, see the description of the AuthenticationMechanismEnumeration (http://go.microsoft.com/fwlink/?LinkID=144382) in theMicrosoft Developer Network (MSDN) library.
CAUTION: Credential Security Support Provider (CredSSP) authentication, in which the user's credentials are passed to a remote computer to be authenticated, is designed for commands that require authentication on more than one resource, such as accessing a remote network share. This mechanism increases the security risk of the remote operation. If the remote computer is compromised, the credentials that are passed to it can be used to control the
network session.
.EXAMPLE
PS C:\> Get-WindowsVersion
ProductName : Windows 10 Pro
EditionID : Professional
ReleaseId : 1809
Build : 17763.195
InstalledUTC : 12/17/2018 2:18:37 PM
Computername : BOVINE320
Query the local host.
.EXAMPLE
PS C:\scripts> get-windowsversion -Computername srv1,srv2,win10 -Credential company\artd | format-table
ProductName EditionID ReleaseId Build InstalledUTC Computername
----------- --------- --------- ----- ------------ ------------
Windows Server 2016 Standard Evaluation ServerStandardEval 1607 14393.2273 12/26/2018 4:07:25 PM SRV1
Windows Server 2016 Standard Evaluation ServerStandardEval 1607 14393.2273 12/26/2018 4:08:07 PM SRV2
Windows 10 Enterprise Evaluation EnterpriseEval 1703 15063.1387 12/26/2018 4:08:11 PM WIN10
Get windows version information from remote computers using an alternate credential.
.Example
PS C:\> Get-WindowsVersion -Computername win10 -AsString
Windows 10 Enterprise Evaluation Version 1703 (OS Build 15063.1387)
Get a string
.INPUTS
System.String
.OUTPUTS
Custom object
.NOTES
Learn more about PowerShell: http://jdhitsolutions.com/blog/essential-powershell-resources/
.LINK
WinVer.exe
.LINK
Invoke-Command
#>
[cmdletbinding()]
[OutputType("custom object")]
[alias('wver')]
Param (
[Parameter(ValueFromPipeline,ValueFromPipelineByPropertyName, Position = 0)]
[ValidateNotNullOrEmpty()]
[string[]]$Computername = $env:COMPUTERNAME,
[PSCredential]$Credential,
[switch]$UseSSL,
[Int32]$ThrottleLimit,
[ValidateSet('Default', 'Basic', 'Credssp', 'Digest', 'Kerberos', 'Negotiate', 'NegotiateWithImplicitCredential')]
[ValidateNotNullorEmpty()]
[string]$Authentication = "default"
)
Begin {
Write-Verbose "Starting $($MyInvocation.Mycommand)"
$sb = {
$RegPath = 'HKLM:\SOFTWARE\Microsoft\Windows nt\CurrentVersion\'
Get-ItemProperty -Path $RegPath | Select-Object -Property ProductName, EditionID, ReleaseID,
@{Name = "Build"; Expression = {"$($_.CurrentBuild).$($_.UBR)"}},
@{Name = "InstalledUTC"; Expression = { ([datetime]"1/1/1601").AddTicks($_.InstallTime) }},
@{Name = "Computername"; Expression = {$env:computername}}
} #close scriptblock
#update PSBoundParameters so it can be splatted to Invoke-Command
$PSBoundParameters.Add("ScriptBlock", $sb) | Out-Null
$PSBoundParameters.add("HideComputername", $True) | Out-Null
} #begin
Process {
if (-Not $PSBoundParameters.ContainsKey("Computername")) {
#add the default value if nothing was specified
$PSBoundParameters.Add("Computername", $Computername) | Out-Null
}
$PSBoundParameters | Out-String | Write-Verbose
$results = Invoke-Command @PSBoundParameters | Select-Object -Property * -ExcludeProperty RunspaceID, PS*
if ($AsString) {
#write a version string for each computer
` foreach ($result in $results) {
"{0} Version {1} (OS Build {2})" -f $result.ProductName, $result.releaseID, $result.build
}
}
else {
$results
}
} #process
End {
Write-Verbose "Ending $($MyInvocation.Mycommand)"
} #end
} #close function
Function Get-WindowsVersionString {
<#
.SYNOPSIS
Get Windows version information
.DESCRIPTION
This is a PowerShell version of the winver.exe utility. This commands uses PowerShell remoting to query the registry on a remote machine to retrieve Windows version information.The parameters are the same as in Invoke-Command. The command writes a string of version information.
.PARAMETER Computername
Specifies the computers on which the command runs. The default is the local computer.
When you use the ComputerName parameter, Windows PowerShell creates a temporary connection that is used only to run the specified command and is then closed. If you need a persistent connection, use the Session parameter.
Type the NETBIOS name, IP address, or fully qualified domain name of one or more computers in a comma-separated list. To specify the local computer, type the computer name, localhost, or a dot (.).
To use an IP address in the value of ComputerName , the command must include the Credential parameter. Also, the computer must be configured for HTTPS transport or the IP address of the remote computer must be included in the WinRM TrustedHosts list on the local computer. For instructions for adding a computer name to the TrustedHosts list, see "How to Add a Computer to the Trusted Host List" in about_Remote_Troubleshooting.
On Windows Vista and later versions of the Windows operating system, to include the local computer in the value of ComputerName , you must open Windows PowerShell by using the Run as administrator option.
.PARAMETER Credential
Specifies a user account that has permission to perform this action. The default is the current user.
Type a user name, such as User01 or Domain01\User01. Or, enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, this cmdlet prompts you for a password.
.PARAMETER UseSSL
Indicates that this cmdlet uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer. By default, SSL is not used.
WS-Management encrypts all Windows PowerShell content transmitted over the network. The UseSSL parameter is an additional protection that sends the data across an HTTPS, instead of HTTP.
If you use this parameter, but SSL is not available on the port that is used for the command, the command fails.
.PARAMETER ThrottleLimit
Specifies the maximum number of concurrent connections that can be established to run this command. If you omit this parameter or enter a value of 0, the default value, 32, is used.
The throttle limit applies only to the current command, not to the session or to the computer.
.PARAMETER Authentication
Specifies the mechanism that is used to authenticate the user's credentials. The acceptable values for this
parameter are:
- Default
- Basic
- Credssp
- Digest
- Kerberos
- Negotiate
- NegotiateWithImplicitCredential
The default value is Default.
CredSSP authentication is available only in Windows Vista, Windows Server 2008, and later versions of the Windows operating system.
For information about the values of this parameter, see the description of the AuthenticationMechanismEnumeration (http://go.microsoft.com/fwlink/?LinkID=144382) in theMicrosoft Developer Network (MSDN) library.
CAUTION: Credential Security Support Provider (CredSSP) authentication, in which the user's credentials are passed to a remote computer to be authenticated, is designed for commands that require authentication on more than one resource, such as accessing a remote network share. This mechanism increases the security risk of the remote operation. If the remote computer is compromised, the credentials that are passed to it can be used to control the
network session.
.EXAMPLE
PS C:\> Get-WindowsVersionString -Computername win10 -credential company\artd
Windows 10 Enterprise Evaluation Version 1703 (OS Build 15063.1387)
Get a string version of Windows version information from a remote computer and use an alternate credential.
.EXAMPLE
PS C:\> Get-WindowsVersionString
Windows 10 Pro Version 1809 (OS Build 17763.195)
Get version information for the current computer.
.EXAMPLE
PS C:\> import-csv .\company.csv | Select Computername,@{Name="Version";Expression={ get-windowsversionstring $_.computername}}
Computername Version
------------ -------
Dom1 Windows Server 2016 Standard Evaluation Version 1607 (OS Build 14393.2273)
Srv1 Windows Server 2016 Standard Evaluation Version 1607 (OS Build 14393.2273)
Srv2 Windows Server 2016 Standard Evaluation Version 1607 (OS Build 14393.2273)
Win10 Windows 10 Enterprise Evaluation Version 1703 (OS Build 15063.1387)
Import data from a CSV file and display version information.
.INPUTS
System.String
.OUTPUTS
System.String
.NOTES
Learn more about PowerShell: http://jdhitsolutions.com/blog/essential-powershell-resources/
.LINK
Get-WindowsVersion
.LINK
Winver.exe
#>
[cmdletbinding()]
[OutputType("system.string")]
Param (
[Parameter(ValueFromPipeline, ValueFromPipelineByPropertyName, Position = 0)]
[ValidateNotNullOrEmpty()]
[string[]]$Computername = $env:COMPUTERNAME,
[PSCredential]$Credential,
[switch]$UseSSL,
[Int32]$ThrottleLimit,
[ValidateSet('Default', 'Basic', 'Credssp', 'Digest', 'Kerberos', 'Negotiate', 'NegotiateWithImplicitCredential')]
[ValidateNotNullorEmpty()]
[string]$Authentication = "default"
)
Begin {
Write-Verbose "Starting $($MyInvocation.Mycommand)"
} #begin
Process {
$results = Get-WindowsVersion @PSBoundParameters
#write a version string for each computer
` foreach ($result in $results) {
"{0} Version {1} (OS Build {2})" -f $result.ProductName, $result.releaseID, $result.build
}
} #process
End {
Write-Verbose "Ending $($MyInvocation.Mycommand)"
} #end
}
หากคุณเลื่อนโค้ดสำหรับเทมเพลต Get-Something ของฉันลง คุณจะเห็นบล็อกความคิดเห็นที่ส่วนท้ายของไฟล์ นี่คือข้อมูลโค้ด json คุณคัดลอกและวางสิ่งนี้ลงในไฟล์ json ตัวอย่าง PowerShell สำหรับ VSCode หากคุณไม่ทราบวิธีไปที่นั่น ให้คลิกไอคอนรูปเฟืองและเลือก User Snippets เลือกไฟล์ powershell.json วางข้อมูลโค้ดลงในไฟล์นี้ ดูเครื่องหมายจุลภาคของคุณ!
ด้วยตัวอย่างนี้ ฉันสามารถสร้างฟังก์ชันใหม่ได้อย่างรวดเร็วโดยเริ่มพิมพ์ 'get-something'
กด Enter เพื่อแทรกข้อมูลโค้ด เพิ่ม scriptblock ของคุณ (ซึ่งคุณรู้อยู่แล้วว่าใช้งานได้ใช่ไหม) ปรับพารามิเตอร์ อัปเดตความช่วยเหลือ แค่นี้ก็เสร็จแล้ว!
ฉันหวังว่าคุณจะพบว่าบทความสองสามข้อสุดท้ายเหล่านี้มีประโยชน์ในการสร้างสคริปต์และฟังก์ชัน PowerShell ของคุณเอง ผลลัพธ์สุดท้ายของฉันไม่ใช่เป้าหมายและจริงๆ แล้วไม่ได้เกี่ยวข้องกันขนาดนั้น สิ่งสำคัญที่คุณควรมุ่งเน้นคือกระบวนการและรูปแบบในการสร้างเครื่องมือ PowerShell หากคุณสามารถ "ปรับขนาดเทมเพลต" ได้ก็ยิ่งดีเท่านั้น ความคิดเห็นของคุณยินดีต้อนรับเสมอ ฉันสนใจมากว่าคุณต้องเผชิญอุปสรรคอะไรหรือสิ่งที่คุณพบว่าเข้าใจยาก คุณอาจสนใจหนังสือการเขียนสคริปต์และการสร้างเครื่องมือของ PowerShell ในการเรียนรู้กระบวนทัศน์และแนวคิดการเขียนสคริปต์เพิ่มเติม