PowerShell 脚本(Scripts)

对于经常用或者重要的脚本,可以保持到本地文件中,需要的时候可直接调用,这样处理更加方便!

编写脚本输出到文件 (若不指定绝对路径,默认都使用当前目录)

"Get-Date" > MyScript.ps1 
"pwd" >> MyScript.ps1 
"‘测试‘" >> MyScript.ps1 
"Get-Date 
pwd 
‘测试‘" > MyScript.ps1 
#或者使用 @‘‘@ 批量写入 
@‘ 
Get-Date 
pwd 
"测试" 
‘@ > MyScript.ps1

    相关操作:

    #执行文本脚本 
    .\MyScript.ps1 
    #获取脚本到PS控制台 
    Get-Content .\MyScript.ps1 
    #打开文本文件 
    notepad MyScript.ps1


      1. #新建或更新脚本,脚本中使用参数 
        notepad MyScript.ps1 
        Write-Host "Hello,$args" 
        .\MyScript.ps1 kk

      脚本中的参数用法与函数内部定义一样

      #函数 
      Function Test{     
      begin{ $i=1 }     
      process{     
           $_.name   
           $i++     
      }     
      end{}     
      }     
      Get-Service -DisplayName "*MSSQLSERVER*" | Test   
      #脚本 notepad MyScript.ps1 
      begin{ $i=1 }     
      process{     
           $_.name   
           $i++     
      }     
      end{}

        管道中执行的脚本:

        #编辑脚本如下 notepad MyScript.ps1 
        foreach ($element in $input) 
        { 
            if($element.Extension -eq ".exe") 
            { 
                Write-Host -fore "red" $element.Name 
            } 
            else 
            { 
                Write-Host -fore "Green" $element.Name 
            } 
        } 
        #或者使用流处理,编辑脚本如下 notepad MyScript.ps1 
        begin{} 
        process 
        { 
            if($_.Extension -eq ".exe") 
            { 
                Write-Host -fore "red" $_.Name 
            } 
            else 
            { 
                Write-Host -fore "Green" $_.Name 
            } 
        } 
        end{}
          #执行 
          ls $env:windir | .\MyScript.ps1

            设置别名更方便:

            1. #设置别名更方便 
              Set-Alias edit notepad.exe 
              edit MyScript.ps1

            【数字签名证书】

            脚本很容易被替换或者更高,使用签名验证会告诉我们脚本是否信任,是否包含了恶意篡改。

            创建证书:    
            开始——>所有程序——>Microsoft Visual Studio 2012——>Visual Studio Tools——>VS2012 x86 本机工具命令提示    
            或者:    
            C:\Program Files\Windows Kits\8.1\bin\x86\makecat.exe

            makecert.exe -pe -r -n "CN=PowerShellTestCert" -eku 1.3.6.1.5.5.7.3.3 -ss "My"

            查看证书:

            dir Cert:\CurrentUser\My -CodeSigningCert 
            ls cert:CurrentUser\My 
            ls cert:CurrentUser\My | where {$_.subject -eq "CN=PowerShellTestCert"}

              设置数字签名认证:

              $Cert=ls cert:CurrentUser\My | where {$_.subject -eq "CN=PowerShellTestCert"} 
              Set-AuthenticodeSignature -PSPath "MyScript.ps1" -Certificate $Cert 
              edit MyScript.ps1

                   

                签名已经成功!!

                证书相关信息:

                #证书的代表 
                $Cert.subject 
                #证书的签发者 
                $Cert.issuer 
                #证书的序列号,指纹 
                $Cert | select SerialNumber,Thumbprint | fl * 
                #证书是否受信任 
                $Cert.Verify() 
                #打开证书窗口界面 
                [System.Reflection.Assembly]::LoadWithPartialName("System.Security") 
                [System.Security.Cryptography.x509Certificates.X509Certificate2UI]::DisplayCertificate($Cert)

                  上面打开的证书并不受信任!

                  添加信任(或者窗口添加:certmgr.msc)

                  1. $rootStore= New-Object system.security.cryptography.X509Certificates.x509Store("root","Currentuser") 
                    $rootStore.Open("ReadWrite") 
                    $rootStore.Add($Cert) 
                    $rootStore.Close() 
                    $Cert.Verify()

                  操作 Add($Cert) 会提示对话框,点击确认即可!

                  给脚本添加数字签名:

                  1. #给文件(MyScript.ps1)添加签名 
                    Set-AuthenticodeSignature MyScript.ps1 $Cert 
                    Set-AuthenticodeSignature -PSPath "MyScript.ps1" -Certificate $Cert 
                    #给所有文件添加签名 
                    Set-AuthenticodeSignature (ls *.ps1) $Cert 
                    Set-AuthenticodeSignature (Dir -recurse -include *.ps1) $Cert 
                    #文件是否有数字签名 
                    Get-AuthenticodeSignature test.ps1 
                    Get-AuthenticodeSignature MyScript.ps1

                  对于脚本的执行权限,powershell 有几个设置:

                  #设置脚本执行权限 
                  Set-ExecutionPolicy Restricted      #禁止执行脚本 
                  Set-ExecutionPolicy Default     #默认 
                  Set-ExecutionPolicy AllSigned       #只执行数字验证的脚本 
                  Set-ExecutionPolicy RemoteSigned    #本地无需证书,远程需要证书 
                  Set-ExecutionPolicy Unrestricted    #无限制,可执行任何脚本

                    查看当前PS中脚本执行权限:

                    #查看当前PS中脚本执行权限 
                    Get-ExecutionPolicy 
                    Get-ExecutionPolicy -List

                      现在设置为只有数字签名的文件可执行:

                      #现在设置为数字签名可执行 
                      Set-ExecutionPolicy AllSigned

                        执行脚本(第一个无签名,报错;第二个有签名,正常执行)

                        #执行脚本(第一个无签名,报错;第二个有签名,正常执行) 
                        ls $env:windir | .\test.ps1 
                        Get-Service -DisplayName "*MSSQLSERVER*" | .\MyScript.ps1

                          现在我把文件内容篡改:

                          执行脚本,出错!

                          完美!~

                          时间: 2024-08-25 08:28:37

                          PowerShell 脚本(Scripts)的相关文章

                          PowerShell 脚本执行策略

                          为防止恶意脚本的执行,PowerShell 中设计了一个叫做执行策略(Execution Policy)的东西(我更倾向于把它叫做脚本执行策略).我们可以在不同的应用场景中设置不同的策略来防止恶意脚本的执行.本文主要是解释这些执行策略,因为笔者在学习的时候发现它们并不是那么清晰易懂.PowerShell 提供了 Restricted.AllSigned.RemoteSigned.Unrestricted.Bypass.Undefined 六种类型的执行策略,接下来我们一一介绍. Restrict

                          PowerShell脚本授权最佳实践

                          [TechTarget中国原创] Windows PowerShell已成为微软在Windows Server上提供的首选管理界面.因为深度整合到Windows Server操作系统,PowerShell表面看上去可以不受任何限制做任何事情.然而,实际上能做得并没有那么多. Windows Server最好用的功能之一就是可以运行脚本.PowerShell脚本允许代码重复使用,并支持运行复杂的命令序列,这是其他方式无法实现的. PowerShell脚本的编写者必须关注的一个大问题就是授权.Pow

                          powershell脚本自动检核DAG

                          经常检查DAG复制是Exchange邮箱管理员日常任务之一,以前每天上去看也挺烦的,尤其数据库比较多的情况下.下图就是"好心"的台北同事经常提醒我检查,我的天,这要是通过EMC看还不累死.还CC我领导,搞的人怪没面子的. 几条需要注意: 一.此脚本放在exchange任一台主机运行即可. 二.Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 添加Exchange管理模块 三.用Get-MailboxDatabase

                          云服务程序在启动的时候执行Powershell脚本

                          如果在云服务程序启动时候,需要执行Powershell脚本,我们需要将脚本嵌入到程序中,并且编写一个cmd来执行这个脚本,具体如下: 1.编写测试的Powershell脚本:每隔10分钟 检测dns $TimeStart = Get-Date $TimeEnd = $timeStart.addminutes(1440) $name = "cnppmedia.blob.core.chinacloudapi.cn." $result = "d:\nslookuplog.txt&q

                          C#调用PowerShell脚本

                          今天通过一个小例子,学习了C#如何调用PowerShell脚本文件的Function以及传参. private bool CallPowershell(string outputFile) { string ddcHost = "test"; RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create(); Runspace runspace = RunspaceFactory.CreateRun

                          powershell脚本,命令行参数传值,并绑定变量的例子

                          这是小技巧文章,所以文章不长.但原创唯一,非常重要.我搜了下,还真没有人发 powershell怎样 [命令行 参数 绑定],所以我决定写成博客. 搜索关键字如下: powershell 命令行 参数 绑定 powershell 传入 参数 powershell 传递 参数 powershell CmdletBinding powershell 命令行 参数 绑定 传入 传递 parameter CmdletBinding powershell 传教士 原创文章.始于 2016-09-26 允许

                          Powershell脚本实时获取所有cpu使用时间非0的进程

                          Powershell脚本实时获取所有cpu使用时间非0的进程,并将名称一致的进程合并. #定义结果输出路径 $OutFile = "D:\CPU_" + (Get-Date).GetDateTimeFormats()[1] + ".csv" #定义性能收集器对象 $CpuCores = (Get-WMIObject Win32_ComputerSystem).NumberOfLogicalProcessors $Processes = Get-Counter &qu

                          强制PowerShell脚本以管理员权限运行

                          param( $a, $b ) #region 关键代码:强迫以管理员权限运行 $currentWi = [Security.Principal.WindowsIdentity]::GetCurrent() $currentWp = [Security.Principal.WindowsPrincipal]$currentWi if( -not $currentWp.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))

                          今天在写powershell脚本中犯的两个错误

                          可能是因为牙痛没睡好,今天老是犯错,还是脚本写错,特别难调. 第一个错误: powershell脚本里面,函数与函数互相调用的传参.其实就像调用普通的cmdlet一样的写法,应该这么写: Add-ScopeObject -adminAddr $adminAddr -name $newScope.Name -objectList $objectList 看我写成啥: Add-ScopeObject($adminAddr, $newScope.Name, $objectList) 结果怎么都执行不对

                          WindowsAzure Powershell脚本定时启动关机Azure VM

                          说到windowsazure对于当下不是一个新鲜话题了,但是对于功能来说还是有点期待的,毕竟在云服务的世界里windowsazure还是一个菜鸟了.同样我们都知道,对于windowsazure上的服务操作我们有很多方式可以操作,比如:portal页面,powershell with azure及azure pack等,其他的都是图形界面操作,操作相对简单,今天咱们就说说通过windows azure powershell命令来管理windows azure上的部分服务,powershell操作命