powershell命令学习_weixin_34051201的博客-程序员秘密

技术标签: 运维  shell  数据库  

#实例化对象,以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  [email protected]
    
    CreateAccount.ps1 -accountName 
" userTest "  -password  " P @ s5w0rd "  -computerName= " stswormdan1 "
    Create a account named userTest on stswormdan1  ,and specify the password as  [email protected]
    
    
" @
    
  
$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"
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_34051201/article/details/86374557

智能推荐

oj2408: C语言习题 用递归方法求 f(n)_黯色_的博客-程序员秘密

问题描述:C语言习题 用递归方法求 f(n) = 12+22+...+n2  ,n的值由主函数输入。作者:何知令发表时间:2017年2月13日输入:n的值。输出: f(n) 的值。代码:/*问题描述:C语言习题 用递归方法求 f(n) = 12+22+...+n2 ,n的值由主函数输入。作者:何知令发表时间:2017年2月13日输入:n的值。输出: f(n) 的值。

i.MX6ULL终结者LCD屏幕显示例程eLCDIF接口简介_一只流浪小法师的博客-程序员秘密

LCD液晶屏也是我们常用的外设,通过LCD我们可以方便的和设备进行人机交互,i.MX6 ULL提供了eLCDIF的接口。eLCDIF的全称是Enhanced LCD Interface,即增强型LCD接口。关于LCD我们需要了解下面的几个概念:1.显示分辨率显示分辨率(屏幕分辨率)是屏幕图像的精密度,是指显示器所能显示的像素有多少。由于屏幕上的点、线和面都是由像素组成的,显示器可显示的像素越多,画面就越精细,同样的屏幕区域内能显示的信息也越多,所以分辨率是个非常重要的性能指标。可以把整个图像想象成是一

计算机网络应用基础教学计划,高一计算机网络应用基础教学计划_瓦罗兰十字军的博客-程序员秘密

《高一计算机网络应用基础教学计划》由会员分享,可在线阅读,更多相关《高一计算机网络应用基础教学计划(4页珍藏版)》请在人人文库网上搜索。1、成都市工程职业技术学校学期授课计划授课学期 2015年上学期 课程名称 计算机网络应用基础 适用班级 2014级计算机 1 班 任课教师: 袁冬梅 2015 年 3 月 9 日制订教研组长: 刘清太 2015 年 月 日审查专业部主任: 刘清太 2015 年 ...

Job for network.service failed because the control process exited with error code问题_苦痛自渡~冷暖自知的博客-程序员秘密

在centos7下,输入service network restart 命令,报以下错误 : Job for network.service failed because the control process exited with error code. See “systemctl status network.service” and “journalctl -xe” for details. 下面介绍以下我的解决方法在 /etc/sysconfig/network-scripts目录下删除掉别

随便推点

人脸识别活体检测技术探讨_cookie.law的博客-程序员秘密

人脸识别活体检测技术探讨:多物理特征融合加分类器的算法技术随着人脸识别、人脸解锁等技术在金融、门禁、考勤、人证合一等日常生活中的广泛应用,人脸防伪/活体检测(Face Anti-Spoofing)技术在近年来得到了越来越多的关注。简单来说,活体检测就是要识别出成像设备(摄像头、手机等)上检测到的人脸图像是来自真实的人脸,还是某种形式的攻击或伪装。这些攻击形式主要包括照片(包括纸质照片和手机、平...

HttpWatch+HttpClient模拟登录学校教务系统_zhongjisadan的博客-程序员秘密

因为最近在做一个安卓项目,有查成绩模块,而学校并不提供接口,也没找到其他可用的API,无奈之下只能回归原始的模拟登录。首先,我们得先弄明白我们校园网是怎么工作的,这里要用到HttpWatch,分析我们正常登录时的请求与响应信息,当然你有chrome或fox之类的也行。我个人还是觉得HttpWatch看着要清晰些。没用过HttpWatch的自己下载研究琢磨下,这里不作赘述。我这用的是HttpWatc...

单片机多个串口如何都能使用printf函数_ydb1358396458的博客-程序员秘密

在keil中我们知道如何实现printf的重定向,但是有些单片机有多个串口,这时我想让所有串口都能使用这个printf函数该怎么办呢?http://m.eeworld.com.cn/ic_article/268/39720.html...

企业微信点餐数据库_企业微信 订餐 python_汪小敏同学的博客-程序员秘密

# 微信点餐数据库```sql-- 类目create table `product_category` ( `category_id` int not null auto_increment, `category_name` varchar(64) not null comment '类目名字', `category_type` int not null com...

从技术到体验:机器翻译产品落地实践_Necther的博客-程序员秘密

课程目标:1.聊聊翻译能力落地时需要考虑的方方面面2.如何根据业务需求定制一个翻译模型3.谈谈一些快速提升翻译质量的小技巧为什么要做机器翻译?日常人们如何使用翻译?手机上的翻译产品形态:机器翻译如何落地?目录:做算法前先了解你的业务算法不仅是NMT模型数据决定了翻译效果的上限科学评测指引优化方向工程工作同样很重要做算法前先了解你的业务核心人群:高频场景分析:需要的翻译技术类型:算法不仅是NMT模型总体流程:语种检测:中英文分词:

推荐文章

热门文章

相关标签