Learning note(7) for windows powershell Tips

来源:互联网 发布:金融数据分析发展方向 编辑:程序博客网 时间:2024/06/05 00:36
 
 
  • Windows PowerShell每周提示(18):读取文本文件
 
    1. Get-Content
       

           Get-Content C:/Scripts/Test.txt 

    2. Get-Content读取文本文件并在变量中储存内容时,数据是作为数组储存的,文件内的每一行(由一个回车换行符决定)代表了数组中的每一个项

 

        a. 查看变量类型

             $a = Get-Content C:/Scripts/Test.txt 

             $a.GetType()

 

    3. 只看文本文件的前三行

           

            (Get-Content C:/Scripts/Test.txt)[0..2]

        

    4. 另一个显示开始的x行的方法是使用–totalcount参数

          

             Get-Content C:/Scripts/Test.txt -totalcount 3    


             如果你正在处理一个大文件的话,这是一个更好的方式来显示前三行,因为Get-Content将只会提取前三行。我们刚才向你呈现的那个命令,将提取整个文件,但是仅显示前三项
    
   5. 显示文本文件的最后三行文本

    

               (Get-Content C:/Scripts/Test.txt)[-1..-3]


   6. 打开这个文件,对内容排序,然后显示排序后的内容
  
              (Get-Content C:/Scripts/Test.txt) | Sort-Object
 
   7. 定位包含特定值的文本文件
    
        Select-String C:/Scripts/*.txt -pattern "Hey, Scripting Guy!"
 
             Select-String C:/Scripts/*.txt -pattern "Hey, Scripting Guy!" | Format-List
        
             Select-String C:/Scripts/*.txt -pattern "Hey, Scripting Guy!" | Select-Object Filename
 

 

  • Windows PowerShell每周提示(19):对多台计算机运行Windows PowerShell脚本

    1. 使用命令行参数
       a. 任何Windows PowerShell脚本的命令行参数都支持自动放置在一个特殊的变量$args
                foreach ($i in $args)    
                    

                    {"$i`n=========================="; Get-WMIObject Win32_BIOS -computername $i}


    2. 从文本文件中读取计算机名

        $a = Get-Content "C:/Scripts/Test.txt"

 

        foreach ($i in $a)

            {$i + "`n" + "=========================="; Get-WMIObject Win32_BIOS -computername $i}

   
        => 
 

        foreach ($i in Get-Content "C:/Scripts/Test.txt")

            {$i + "`n" + "=========================="; get-wmiobject win32_bios -computername $i}


 

   3. 提示用户输入计算机名

 

    do

        {

            $a = Read-Host "Please enter the computer name"

            if ($a -ne "")

            {$a + "`n" + "=========================="; Get-WMIObject Win32_BIOS -computername $a}

        }

    while ($a -ne "")    

 

原创粉丝点击