[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖

[问题求助] 初涉Powershell 不懂,求注释

本帖最后由 terse 于 2013-11-1 16:15 编辑

下载了一段Powershell代码  对其中功能的实现不了解 谁能注释下吗 感谢
  1. function Get-WebSite {
  2. <#  
  3. .SYNOPSIS  
  4.     Retrieves information about a website.
  5. .DESCRIPTION
  6.     Retrieves information about a website.
  7. .PARAMETER Url
  8.     URL of the website to test access to.
  9. .PARAMETER UseDefaultCredentials
  10.     Use the currently authenticated user's credentials  
  11. .PARAMETER Proxy
  12.     Used to connect via a proxy
  13. .PARAMETER TimeOut
  14.     Timeout to connect to site, in milliseconds
  15. .PARAMETER Credential
  16.     Provide alternate credentials              
  17. .NOTES  
  18.     Name: Get-WebSite
  19.     Author: Boe Prox
  20.     DateCreated: 08Feb2011        
  21. .EXAMPLE  
  22.     Get-WebSite -url "http://www.bing.com"
  23.      
  24. Description
  25. ------------
  26. Returns information about Bing.Com to include StatusCode and type of web server being used to host the site.
  27. #>
  28. [cmdletbinding(
  29.     DefaultParameterSetName = 'url',
  30.     ConfirmImpact = 'low'
  31. )]
  32.     Param(
  33.         [Parameter(
  34.             Mandatory = $True,
  35.             Position = 0,
  36.             ParameterSetName = '',
  37.             ValueFromPipeline = $True)]
  38.             [string][ValidatePattern("^(http|https)\://*")]$Url,
  39.         [Parameter(
  40.             Position = 1,
  41.             Mandatory = $False,
  42.             ParameterSetName = 'defaultcred')]
  43.             [switch]$UseDefaultCredentials,
  44.         [Parameter(
  45.             Mandatory = $False,
  46.             ParameterSetName = '')]
  47.             [string]$Proxy,
  48.         [Parameter(
  49.             Mandatory = $False,
  50.             ParameterSetName = '')]
  51.             [Int]$Timeout,
  52.         [Parameter(
  53.             Mandatory = $False,
  54.             ParameterSetName = 'altcred')]
  55.             [switch]$Credential           
  56.                         
  57.         )
  58. Begin {     
  59.     $psBoundParameters.GetEnumerator() | % {
  60.         Write-Verbose "Parameter: $_"
  61.         }
  62.    
  63.     #Create the initial WebRequest object using the given url
  64.     Write-Verbose "Creating the web request object"      
  65.     $webRequest = [net.WebRequest]::Create($url)
  66.      
  67.     #Use Proxy address if specified
  68.     If ($PSBoundParameters.ContainsKey('Proxy')) {
  69.         #Create Proxy Address for Web Request
  70.         Write-Verbose "Creating proxy address and adding into Web Request"
  71.         $webRequest.Proxy = New-Object -TypeName Net.WebProxy($proxy,$True)
  72.         }
  73.          
  74.     #Set timeout
  75.     If ($PSBoundParameters.ContainsKey('TimeOut')) {
  76.         #Setting the timeout on web request
  77.         Write-Verbose "Setting the timeout on web request"
  78.         $webRequest.Timeout = $timeout
  79.         }        
  80.      
  81.     #Determine if using Default Credentials
  82.     If ($PSBoundParameters.ContainsKey('UseDefaultCredentials')) {
  83.         #Set to True, otherwise remains False
  84.         Write-Verbose "Using Default Credentials"
  85.         $webrequest.UseDefaultCredentials = $True
  86.         }
  87.     #Determine if using Alternate Credentials
  88.     If ($PSBoundParameters.ContainsKey('Credentials')) {
  89.         #Prompt for alternate credentals
  90.         Write-Verbose "Prompt for alternate credentials"
  91.         $wc.Credential = (Get-Credential).GetNetworkCredential()
  92.         }            
  93.          
  94.     #Set TimeStamp prior to attempting connection   
  95.     $then = get-date
  96.     }
  97. Process {   
  98.     Try {
  99.         #Make connection to gather response from site
  100.         $response = $webRequest.GetResponse()
  101.         #If successful, get the date for comparison
  102.         $now = get-date
  103.          
  104.         #Generate report
  105.         Write-Verbose "Generating report from website connection and response"
  106.         $report = @{
  107.             URL = $url
  108.             StatusCode = $response.Statuscode -as [int]
  109.             StatusDescription = $response.StatusDescription
  110.             ResponseTime = "$(($now - $then).totalseconds)"
  111.             WebServer = $response.Server
  112.             Size = $response.contentlength
  113.             }
  114.         }
  115.     Catch {
  116.         #Get timestamp of failed attempt
  117.         $now = get-date
  118.         #Put the current error into a variable for later use
  119.         $errorstring = "$($error[0])"
  120.          
  121.         #Generate report
  122.         $report = @{
  123.             URL = $url
  124.             StatusCode = ([regex]::Match($errorstring,"\b\d{3}\b")).value
  125.             StatusDescription = (($errorstring.split('\)')[2]).split('.\')[0]).Trim()
  126.             ResponseTime = "$(($now - $then).totalseconds)"
  127.             WebServer = $response.Server
  128.             Size = $response.contentlength
  129.             }   
  130.         }
  131.     }
  132. End {        
  133.     #Display Report   
  134.     New-Object PSObject -property $report
  135.     }   
  136. }  
  137. Get-WebSite -url "http://www.bing.com"
复制代码
  1. function Get-WebPage {
  2. <#  
  3. .SYNOPSIS  
  4.    Downloads web page from site.
  5. .DESCRIPTION
  6.    Downloads web page from site and displays source code or displays total bytes of webpage downloaded
  7. .PARAMETER Url
  8.     URL of the website to test access to.
  9. .PARAMETER UseDefaultCredentials
  10.     Use the currently authenticated user's credentials  
  11. .PARAMETER Proxy
  12.     Used to connect via a proxy
  13. .PARAMETER Credential
  14.     Provide alternate credentials
  15. .PARAMETER ShowSize
  16.     Displays the size of the downloaded page in bytes                 
  17. .NOTES  
  18.     Name: Get-WebPage
  19.     Author: Boe Prox
  20.     DateCreated: 08Feb2011        
  21. .EXAMPLE  
  22.     Get-WebPage -url "http://www.bing.com"
  23.      
  24. Description
  25. ------------
  26. Returns information about Bing.Com to include StatusCode and type of web server being used to host the site.
  27. #>
  28. [cmdletbinding(
  29.     DefaultParameterSetName = 'url',
  30.     ConfirmImpact = 'low'
  31. )]
  32.     Param(
  33.         [Parameter(
  34.             Mandatory = $True,
  35.             Position = 0,
  36.             ParameterSetName = '',
  37.             ValueFromPipeline = $True)]
  38.             [string][ValidatePattern("^(http|https)\://*")]$Url,
  39.         [Parameter(
  40.             Position = 1,
  41.             Mandatory = $False,
  42.             ParameterSetName = 'defaultcred')]
  43.             [switch]$UseDefaultCredentials,
  44.         [Parameter(
  45.             Mandatory = $False,
  46.             ParameterSetName = '')]
  47.             [string]$Proxy,
  48.         [Parameter(
  49.             Mandatory = $False,
  50.             ParameterSetName = 'altcred')]
  51.             [switch]$Credential,
  52.         [Parameter(
  53.             Mandatory = $False,
  54.             ParameterSetName = '')]
  55.             [switch]$ShowSize                       
  56.                         
  57.         )
  58. Begin {     
  59.     $psBoundParameters.GetEnumerator() | % {
  60.         Write-Verbose "Parameter: $_"
  61.         }
  62.    
  63.     #Create the initial WebClient object
  64.     Write-Verbose "Creating web client object"
  65.     $wc = New-Object Net.WebClient
  66.     $wc.Encoding = [System.Text.Encoding]::UTF8
  67.     #Use Proxy address if specified
  68.     If ($PSBoundParameters.ContainsKey('Proxy')) {
  69.         #Create Proxy Address for Web Request
  70.         Write-Verbose "Creating proxy address and adding into Web Request"
  71.         $wc.Proxy = New-Object -TypeName Net.WebProxy($proxy,$True)
  72.         }      
  73.      
  74.     #Determine if using Default Credentials
  75.     If ($PSBoundParameters.ContainsKey('UseDefaultCredentials')) {
  76.         #Set to True, otherwise remains False
  77.         Write-Verbose "Using Default Credentials"
  78.         $wc.UseDefaultCredentials = $True
  79.         }
  80.     #Determine if using Alternate Credentials
  81.     If ($PSBoundParameters.ContainsKey('Credentials')) {
  82.         #Prompt for alternate credentals
  83.         Write-Verbose "Prompt for alternate credentials"
  84.         $wc.Credential = (Get-Credential).GetNetworkCredential()
  85.         }         
  86.          
  87.     }
  88. Process {   
  89.     Try {
  90.         If ($ShowSize) {
  91.             #Get the size of the webpage
  92.             Write-Verbose "Downloading web page and determining size"
  93.             "{0:N0}" -f ($wr.DownloadString($url) | Out-String).length -as [INT]
  94.             }
  95.         Else {
  96.             #Get the contents of the webpage
  97.             Write-Verbose "Downloading web page and displaying source code"
  98.             $wc.DownloadString($url)      
  99.             }
  100.          
  101.         }
  102.     Catch {
  103.         Write-Warning "$($Error[0])"
  104.         }
  105.     }   
  106. }  
  107. Get-WebPage -url "http://www.bing.com"
复制代码
只用一些简单的
  1. $url = 'http://www.bing.com'
  2. $wc = new-object system.net.webclient
  3. $wc.downloadstring($url)
复制代码

同求,我想知道每行前的$符号有什么用.小白,别笑话我

TOP

回复 2# foxJL


    定义变量

TOP

回复 3# DAIC


    我还以为像bat里@的作用。让你贱笑了,呵呵

TOP

本帖最后由 PowerShell 于 2013-11-2 11:24 编辑

$ 打头的都是变量,这个跟php语言类似。这里面我说说powershell语法怎么个好法。
$ 是统一,标准的,也是唯一的。
比如$aaa ,这个变量不管定义,还是引用,都要用$ ,比python更容易看懂。比python的【无变量打头符号】定义变量好。powershell这种做法,更容易区分内置关键字,和变量!
    -------我个人认为这比bat的%aaa%  !bbb! 好,有时候我觉得bat的变量真tm乱。

而powershell变量的定义要求,也要比python好:

1比如可以定义任意unicode变量,如 $三顾茅庐 = 3  。总之  .net的unicode支持比python好。
2可以定义数字变量,如 $123 = "a"     ; echo   ($123 + "b")   输出结果为ab
3powershell定义的变量可以数字打头,这python不行。
4重要!你一定要记住:每个变量都是对象,这和vbs,python,相同。
而每种对象,都自带有属性,方法。这就是面向对象开发之妙也~~~
比如$aaa = "abcd"
那么$aaa.toupper()
将返回ABCD



标准,直观,简单,-------我认为【从变量定义的角度】,学powershell比bat更容易菜鸟理解,学习的也快。



-------------------------------------------------------
另外楼主贴的代码是非常规范的代码,规范到国际版了。还有注释,甚至说所有powershell脚本都应该这么写。
1 这是一个函数定义。
2 2-----28行。前面的大段注释都是 默认的,每个参数都是干嘛的,谁写的脚本,如何用等。
<# powershell大段注释语法 #>
# powershell单行注释语法

3 29行-----58行是参数约束
4 59行----137行为函数主体。
4.1 函数的正宗写法是由3部分组成: (详见镇派葵花宝典,即手册中的说明)
Begin { 一般这里初始化变量 }
Process {  一般具体计算 }
end {  一般这里处理输出,或者扫尾工作 }
4.2 函数可以简化,不要上述3个部分。只要一个大括号包起来。如下例:
aaa,aaa2函数,作用完全相同。
----------------------
  1. function  aaa {
  2. begin {}
  3. process {echo  "你好"}
  4. end {}
  5. }
复制代码
---------------
  1. function  aaa2 {
  2. echo  "你好"
  3. }
复制代码
---------------
脚本是写给人看的,是写给用户看的,而不是写给机子看的
用户能看懂、会修改的脚本,才是好脚本。
写易懂的powershell脚本帮人解决问题,进而让用户学会自渔,吾所愿也

TOP

本帖最后由 terse 于 2013-11-2 18:33 编辑

回复 5# PowerShell
无论怎样先谢你的解答
唉~只怪老夫乃天生愚笨,虽得版主指点,也不解心中迷困,
其实代码本身并不复杂 主要powershell很多的类方法都不熟悉啊
这里参数怎么传进去  传进去处理流程怎样
发现下面参数里的 -URL 有和没有一样 是否里面定义HTTP和HTTPS开头就定义给 $URL 呢?
如果要传多个参数怎么调用呢 最多支持几个参数进去  
如每次调用 要变换PROXY的话怎么办 等等
最好有范例出来就好了  或许你们都忙 那就忽略吧
最后还是谢了哦

TOP

1 powershell很多的类方法都不熟悉啊---------我个人不认为初学者应该学。net类,即使学,也学string类,file类,几个浅显的类足矣,等到学powershell一年以上,再学。net类不迟。初学者应该把精力着重于学习语法,和最新的命令,如powershell4.0带的命令。和第三方库,脚本上。这些命令和库能满足绝大多数初学者的需求。如果有此初学者学过vbs,那么学。net类对他来说就简单多了。可以认为。net类是100多个vbs类的扩展。它们用起来类似。

2 参数怎么传进去。-----貌似只有bat bash 无函数,也难传值,其他大多语言都是 [函数 参数1 参数2 ]这样的传。
函数用法 和powershell的内部命令差不多。

3 最多支持几个参数进去 ---这个我还真不知道.或许是255 ? 我只知道传的数据多了,数据类型又是相同的,可以用数组的方式传,这样就只有1个参数,参数数量只限于数组(列表)大小.不过一般函数都不会超过20个不同的参数.

4 发现下面参数里的 -URL 有和没有一样 ---对.
5 如果要传多个参数怎么调用呢 ?  传进去处理流程怎样? ---暂且不答
6 如每次调用 要变换PROXY的话怎么办  ---编写函数时加个proxy参数即可.

2 3 4 5 6 我都没详细回答,因为你是牛人,不是菜鸟啊,你需要置顶帖中的葵花宝典,即官方手册了,
手册分两部分,第一部分为about xxx 讲的是语法.你看语法中about_Functions ,about_Functions_Advanced
等即可.第二部分为库,讲的是每个命令用法.

最后我再凿吧两句:
powershell语法标准学的快,命令=库 强大功能强。故,学一年powershell练出的技能顶学bat,bash五年.
bat bash 都是破铜烂铁,awk sed 都是虾兵蟹将.powershell语言眼中只有python堪称敌手.
脚本是写给人看的,是写给用户看的,而不是写给机子看的
用户能看懂、会修改的脚本,才是好脚本。
写易懂的powershell脚本帮人解决问题,进而让用户学会自渔,吾所愿也

TOP

回复 7# PowerShell
再次谢你耐心的解答
先看会 看懂和看不懂 都要看的 必须的 谢谢

TOP

返回列表