• powershell命令学习


    #实例化对象,以SqlConnection为例子

    $con=new-object System.Data.Sqlclient.SqlConnection("server=.;uid=xxx;pwd=xxx")


    #引用静态方法 Using Static Classes and Methods

    $strMachineName=[System.Environment]::MachineName
    $result=[System.Math]::Pow(2,3)

    #列出以sql开头的进程
    get-process sql*

    #列出所有进程,按照占用的workingset大小降序排列
    get-process | sort-object workingset -desceding 

    #列出本机共享
    get-wmiobject win32_share

    #得到实际的cpu个数

    get-wmiobject -query "select *from Win32_Processor"


    #如何使用if else,foreach ,  得到所有的服务,安装服务状态进行排序   1

    $serviceArray=get-service | sort-object status -descending 
    foreach ($temp in $serviceArray)
    {
        
    if($temp.status -eq "stopped")
        {
             write
    -host "The" $temp.name "is stopped"  -foreground red
        }
        
    elseif($temp.status -eq "running")
        {
             write
    -host "The" $temp.name "is running"  -foreground green
        }
        
    else 
        {
           write
    -host "The" $temp.name "status is " $temp.status -foreground yellow
        }
    }

    #如何使用if else,foreach ,  得到所有的服务,安装服务状态进行排序    2
    get-service | sort-object status -descending |
    foreach {
     
    if($_.status -eq "stopped")
     {
       write
    -host "The" $_.name "is stopped"  -foreground red
     }
     
    elseif($_.status -eq "running")
     {
       write
    -host "The" $_.name "is running"  -foreground green
     }
     
    else 
     {
        write
    -host "The" $_.name "status is " $_.status -foreground yellow
     }
    }

     

     #如何使用switch ,  得到所有的服务,安装服务状态进行排序

    get-service | sort-object status -descending |
    foreach {
    switch($_.status) 
      {
         
    "stopped"
        {
             write
    -host "The" $_.name "is stopped"  -foreground red
        }
        
    "running"
        {
             write
    -host "The" $_.name "is running"  -foreground green
        }
        
    default
        {
           write
    -host "The" $_.name "status is " $_.status -foreground yellow
        }
       }
    }

     #switch 通配符,统计出包含“sql”关键字的字符串数量

    $counter=0
    $stringArray="sqlserver","t-sql","serviceBroker","TDE" |
    foreach {
    switch -wildcard ($_
      {
         
    "*sql*"
        {
            
    $counter++
        }
        
    default
        {
           write
    -host $_ 
        }
       }
    }
    Write
    -host "there are " $counter "terms contain sql"

     
    #switch 正则表达式

    $stringArray="sqlserver","t-sql","serviceBroker","TDE","The version of sqlserver is 2008, and the edition is enterprise" |
    foreach {
    switch -regex ($_
      {
         
    "sql.*?\d+"#包含sql,并且后面至少有一个数字
        {
               write
    -host $_ -foreground red
        }
        
    default
        {
           write
    -host $_ 
        }
       }
    }


     #得到状态为"运行"的服务 get-service

    $strState="running"
    get
    -service | where-object {$_.status -eq $strState}


    #得到状态为"运行"的服务 get-wmiobject

    $strState="running"
    get
    -wmiobject win32_service -Filter "state='$strState'"

    #将内容写入文件, out-file cmdlet

    $strState="running"
    $strPath="c:\runningService.txt"
    get
    -service | where-object {$_.status -eq $strState| out-file -filepath $strPath

     #查找字符串

    param($folder="C:\TEMP",$keywords="*xyz*"$extension=".txt")

    $files=get-childitem $folder -recurse | where {$_.extension  -eq $extension } |
    foreach($_){
    $fileFullName= $_.FullName
    $content=get-content $fileFullName
    switch -wildcard ($content)
     {
                    
    $keywords
                    {
                                    write
    -host $fileFullName
                    }
                    
    default
                    {
                                   
    # write-host $content
                    }
     }
    }

    findkeyword.zip


    #wmi
    win32_share 设置共享信息:最大访问人数,描述信息

    SetShareInfo Method of the Win32_Share Class

    param($shareName="portfromkj"$maxAllowed=5$description="Test script")

    Function funlookup($intIN)
    {
    Switch($intIN)
    {
    0 { "Success" }
    2 { "Access denied" }
    8 { "Unknown failure" }
    9 { "Invalid name" }
    10 { "Invalid level" }
    21 { "Invalid parameter" }
    22 { "Duplicate share" }
    23 { "Redirected path" }
    24 { "Unknown device or directory" }
    25 { "Net name not found" }
    DEFAULT { "$intIN is an Unknown value" }
    }
    }

    $objService=Get-WmiObject -query "select *from win32_share where name='$shareName'"
    $errRTN=$objService.setShareInfo($maxAllowed,$description)
    funlookup(
    $errRTN.returnValue)

    #win32_service 改变启动模式

    ChangeStartMode Method of the Win32_Service Class

    $serviceName="MSSQL`$MSSQLSERVER3"
    $objService=(get-wmiobject -query "select * from win32_service where name = '$serviceName'").changestartmode("Automatic"#Manual ,#Disabled 

     
    #wmiclass  创建共享

    $folderPath="c:\test"
    $shareName="shareNameTest"
    $maxAccessValue=5
    $description="this is description"
    $type=0
    $objWMI=[wmiClass]"win32_share"
    $objWMI.Create($folderPath,$shareName,$type,$maxAccessValue,$description)

    #配置DNS address和DNS suffiex.

    $DNSServers="10.193.92.10","10.198.38.253","10.198.38.254","157.56.236.138","10.193.70.10","157.54.14.146","157.54.27.50","157.55.254.211","157.54.105.23"
    $NICs=get-wmiobject -query "select * from win32_networkadapterconfiguration where ipenabled='true'"
    Foreach($NIC in $NICs) {
    $NIC.SetDNSServerSearchOrder($DNSServers)
    }
    #dnssuffix
    $DNSSuffixSearchOrder="10.193.92.10,10.198.38.253,10.198.38.254,157.56.236.138,10.193.70.10,157.54.14.146,157.54.27.50"
    $path="HKLM:\System\CurrentControlSet\Services\TCPIP\Parameters\"
    set
    -itemproperty -path $path -name "SearchList" -value $DNSSuffixSearchOrder 

    #createAccount

    代码
    param($computerName$accountName,$password)


    function funhelp()
    {
    $helpText=@"
       
       NAME:CreateAccount.ps1
       Create a account on a local or remote machine, Please specify the account name and password.
       
       PARAMETERS:
       -accountName  specifies the account name you want to create
       -password     speecifes the password 
       -computerName  [optional] it's local machine by default
       
       SYNTAX:
         CreateAccount.ps1 -accountName 
    "userTest" -password "P@s5w0rd"
        Create a account named userTest on local machine ,and specify the password as  P@s5w0rd
        
        CreateAccount.ps1 -accountName 
    "userTest" -password "P@s5w0rd" -computerName="stswormdan1"
        Create a account named userTest on stswormdan1  ,and specify the password as  P@s5w0rd
        
        
    "@
        
      
    $helpText
       exit
    }


    if(!($accountName-or !($password))
    {
       funhelp
    }



    if(!($computerName))
    {
    $computerName =(Get-WmiObject -Query "select *from Win32_ComputerSystem" | Select-Object name).name
    }

    $comp = [adsi] "WinNT://$computerName"     
    $user = $comp.Create("User"$accountName)      
    $user.SetPassword($password)   
    $user.SetInfo()

    Write
    -Host "Account $accountName created in machine $computerName"

    #createFolder

    代码
    param($computerName$folderPath)


    function funhelp()
    {
    $helpText=@"
       
       NAME:CreateFolder.ps1
       Create a  folder on a local or remote machine
       
       PARAMETERS:
       -folderPath    specifies the path of folder you want to create
       -computerName  [optional] it's local machine by default
       
       SYNTAX:
         CreateFolder.ps1 -folderPath 
    "c:\folder1"
        Create a share folder mapping the c:\folder1 on local machine 
        
         CreateFolder.ps1 -folderPath 
    "c:\folder1"  -computerName stswordman1
        Create a share folder mapping the c:\folder1 on computer stswordman1 
        
        
    "@
        
      
    $helpText
       exit
    }


    if(!($folderPath))
    {
       funhelp
    }

    if(!($computerName))
    {
      
    $computerName="."
    }

    $p = [WMIClass]"\\$computerName\root\cimv2:Win32_Process"
    $p.Create("cmd.exe /c md $folderPath")

    Write
    -Host "Account $folderPath created in machine $computerName"

    #zip

    代码
    param($filePath$folderPath,$allInOne="false")


    function funhelp()
    {
    $helpText=@"
       
       NAME:Zip.ps1
       compress file as zip format
       
       PARAMETERS:
       -filePath       specifies the file you want to zip
       -folderPath     specifes the folderPath you want to zip
       -allInOne       only takes effect when you specifies the -folderPath parameter
       Warning: the -filePath can't exist at the same time.
       
       SYNTAX:
         zip.ps1 -filePath 
    "c:\1.txt" 
        compress the file c:\1.txt and name as 1.txt.zip
        
        zip.ps1 -folderPath 
    "c:\1" 
        compress all files under folder c:\1 recursively as separate zip file.
        
        
    "@
        
     Write
    -Host -ForegroundColor green $helpText
       exit
    }



    function out-zip { 
      
    Param([string]$path

      
    if (-not $path.EndsWith('.zip')) {$path += '.zip'} 

      
    if (-not (test-path $path)) { 
        set
    -content $path ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18)) 
      } 
      
    $ZipFile = (new-object -com shell.application).NameSpace($path
      
    $input | foreach {$zipfile.CopyHere($_.fullname)} 



    if(!($filePath-and !($folderPath))
    {
       funhelp
    }


    if($filePath)
    {
     
       Get
    -Item $filePath | out-zip $filePath".zip"
       Write
    -Host "1Compress $filePath completed"
    }
     
    elseif($folderPath)
    {
       
    if($allInOne -eq "true")
       {
       }
       
    else
       {
       
            Get
    -ChildItem $folderPath -Recurse | Select-Object name,directoryName |
         
    foreach($_){
            
    $fileName=$_.fullName
            
    $folderName=$_.directoryName
            Get
    -Item $fileName | out-zip $fileName".zip"
        
    #    write-host $folderName"."$fileName".zip"
        #    Write-Host "Compress $fileName completed "
         }
       }
    }

    #Add a domain user to the local Administrators group on the local or a remote computer 

    代码
    # Add a domain user to the local Administrators group on the local or a remote computer  
      
    $computerName = Read-Host 'Enter computer name or press <Enter> for localhost'  
    $userName = Read-Host 'Enter user name'  
      
    if ($computerName -eq "") {$computerName = "$env:computername"}  
    [string]
    $domainName = ([ADSI]'').name  
    ([ADSI]
    "WinNT://$computerName/Administrators,group").Add("WinNT://$domainName/$userName")  
      
    Write
    -Host "User $domainName\$userName is now local administrator on $computerName." 

    #read log 

     get-eventlog -logname security -computername stswordman2

    #performacne counter

    $counterList="\physicalDisk(*)\Avg. Disk sec/Read","\physicalDisk(*)\Avg. Disk sec/Write","\PhysicalDisk(*)\Disk Reads/sec","\PhysicalDisk(*)\Disk Writes/sec","\PhysicalDisk(*)\Disk Bytes/sec","\PhysicalDisk(*)\Avg. Disk Read Queue Length","\PhysicalDisk(*)\Avg. Disk Write Queue Length"
    $computername="stswordman"
    $interval=15
    $path="c:\pessrformance.blg";
    get
    -Counter -computername $computername -Counter $counterList  -MaxSamples 60 -SampleInterval $interval  | export-counter -max 1 -path  $path

     #monitor Disk

    代码
    function SaveToTable($computerName,$driveID,$freeGB,$totalGB)
    {
    }
    function DiskMonitor($computerName)
    {
        
    #报告可用容量小于10GB或者30%的硬盘
        $diskspaceArrayList=Get-WmiObject -ComputerName $computerName -query "Select * from Win32_logicaldisk where driveType=3"  | select-object DeviceID,Freespace ,Size
        
    foreach ($singleDiskDriver in $diskspaceArrayList)
        {
            
    $driverID=$singleDiskDriver.DeviceID
            
    $FreeGB=[int]($singleDiskDriver.Freespace/(1024*1024*1024))
            
    $TotalGB=[int]($singleDiskDriver.Size/(1024*1024*1024))
            
    $precent=([int]($FreeGB*10000/$TotalGB))/100

            SaveToTable 
    $computerName $driveID $freeGB $totalGB
            
    if( ($FreeGB -lt 10-or ($precent -lt 30) )
            {
                write
    -host "The freespace in Drive $driverID of computer $computerName is low, the avaialbe space is $FreeGB GB , precent=$precent % .The total size is $TotalGB GB"  -foreground Yellow  
            }
        }
    }


    Write
    -Host "------------------- Low Disk ---------------------------"
    Write
    -Host "This script will oupput all the disks which capacity is less than 10Gb or the precent is less than 30%"
    Write
    -Host "------------------- Low Disk ---------------------------"
    $computerList=#...
    foreach($computer in $computerList)
    {
        DiskMonitor (
    $computer)
    }

     创建自定义类

     $source = @"
        public class PerformanceCounter
        {
            private string counterPath;
            private double value;
            private  System.DateTime date;
            public PerformanceCounter(string counterPath, double value,System.DateTime date)
            {
                this.counterPath = counterPath;
                this.value = value;
                this.date=date;
               
            }

            public double Value
            {
                get { return this.value; }
            }
            
             public string CounterPath
            {
                get { return this.counterPath; }
            }
             public string Date
            {
                get { return this.date.ToString(); }
            }

         
        }
    "@

        Add
    -Type -TypeDefinition $source
        
    $basicTestObject = New-Object PerformanceCounter("1",2.2,  [System.DateTime]::now);
        
    $basicTestObject.Value;
        
    $basicTestObject.CounterPath;
        
    $basicTestObject.Date;

      get-process  iexplore | foreach {stop-process $_.id}

    add domain user to local group

    $objUser = [ADSI]("WinNT://domainName/domainUserName")
    $objGroup = [ADSI]("WinNT://machineName/Administrators")
    $objGroup.PSBase.Invoke("Add",$objUser.PSBase.Path)

    remove domain user to local group

    $objUser = [ADSI]("WinNT://domainName/domainUserName")
    $objGroup = [ADSI]("WinNT://machineName/Administrators")
    $objGroup.PSBase.Invoke("Remove",$objUser.PSBase.Path)

     更改SQLSERVER/agent启动账号

    $strUserName = "domainname\user"
    $strPassword= "asdfsfsfsdf112211"
    $computerName="xxxxxx"
    $sqlservice = Get-WmiObject -computername $computerName –namespace root\Microsoft\SqlServer\ComputerManagement10 -class SqlService –filter "ServiceName='MSSQLSERVER'"
    $sqlservice.SetServiceAccount($strUserName$strPassword)
    $sqlservice.StopService()
    $sqlservice.StartService()
    $sqlservice = Get-WmiObject -computername $computerName –namespace root\Microsoft\SqlServer\ComputerManagement10 -class SqlService –filter "ServiceName='SQLSERVERAGENT'"
    $sqlservice.SetServiceAccount($strUserName$strPassword)
    $sqlservice.StartService()

     http://sqlmag.com/powershell/using-sql-server-management-objects-powershell

    Method 1. If you're using PowerShell 1.0, you can load a .NET assembly for that PowerShell version using the command:

    [System.Reflection.Assembly]::LoadWithPartialName                                 ("Microsoft.SqlServer.Smo");

                                  (Although this command wraps here, you need to enter it all on one line in the PowerShell console.) This command will grab the latest SMO installed in your system. You can also use this method with PowerShell 2.0 and later.

    Method 2. In PowerShell 2.0 and later, you can use the Add-Type cmdlet to load the Microsoft.SqlServer.Smo assembly:

    Add-Type -AssemblyName "Microsoft.SqlServer.Smo"

                                  Unfortunately, this command won't work if you have multiple SQL Server versions installed on your machines. In addition, you might also encounter an error message if you're running it on a single SQL Server 2012 instance. This is a known bug that has been reported to Microsoft.

    Method 3. This method is a workaround if you're using PowerShell 2.0 or later but Method 2 doesn't work. In this workaround, you use the full SMO assembly path in the command:

    Add-Type -path `                               "C:\Windows\assembly\GAC_MSIL\Microsoft.SqlServer.Smo\                                 10.0.0.0__89845dcd8080cc91\Microsoft.SqlServer.Smo.dll"
  • 相关阅读:
    2012搜狗校园招聘笔试题(2)
    T-SQL中只截取日期的日期部分和日期的时间部分
    Delphi XE4 TStringHelper用法详解
    TScreen 类
    TScreen 类
    Delphi中Form的position属性与代码自定义窗体位置
    如何让窗口显示在电脑屏幕中间
    C#中整型数据类型
    C# WinForm开发系列
    SQL中EXCEPT和Not in的区别?
  • 原文地址:https://www.cnblogs.com/stswordman/p/1578200.html
Copyright © 2020-2023  润新知