windows powershell 命令 持续更新

1、windows powershell 非交互修改密码:

net user 账号 新密码

 net user administrator   qazwsx123456
2、for循环:
foreach ($n in  11,22,33)
    {echo  $n }

执行结果:
11
22
33
3、if判断:

if( 片段条件 ) { 判断为 “ 真 ” 执行的命令 } else { 判断为 “ 假 ” 执行的命令 }

if(1 -eq 1)
{"true"}
else
{"false"}

执行结果:
true

比较运算符:

-eq :等于
-ne :不等于
-gt :大于
-ge :大于等于
-lt :小于
-le :小于等于
-contains :包含
-notcontains :不包含

布尔运算符:
-and :和
-or :或
-xor :异或
-not :逆
!($var)

  • 判断目录是否存在(也可以判断文件)
if ( Test-Path c:\RZY ) { echo 1 } else { echo 2 }
switch 与 linux的case作用一样
Switch ($num)
{
    1 { 表达式 }
    2 { 表达式 }
}
4、类似awk的用法(取本机第一个IP):

%{$_.split("-")[0]} : 表示 ("-") 为指定分隔符 "-" ; [0] 取第一个;[-1]取最后一个

#取出IP地址,并以" - " 隔开(本机有多个IP)
$server_ip1=(Get-IPAddress |Select-Object -ExpandProperty IPAddressV4  MacAddress) -join "-"
PS C:\> echo $server_ip1
10.27.82.113-10.127.127.1-169.254.54.52-10.0.0.1

#取第一个IP地址
$server_ip1|%{$_.split("-")[0]}

取IP地址:

Get-IPAddress |Select-Object -ExpandProperty IPAddressV4  MacAddress
  • 经过实践,上面取IP的方法不通用,下面的方法通用性更强

取 10.1x.xx.xx网段的IP地址

$IP_ADD=([System.Net.Dns]::GetHostAddresses($ComputerName) |Where-Object {  $_.AddressFamily -eq 'InterNetwork' } | Select-Object -ExpandProperty IPAddressToString|findstr "10.1") -join "-" 

$IP_ADD=$IP_ADD|%{$_.split("-")[0]}
echo  $IP_ADD

5、获取DNS
Get-CimInstance -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=$true | Select-Object -ExpandProperty dnsserversearchorder
6、添加指定分隔符
PS C:\Users\Administrator> $aa="a1 a2 a3"
PS C:\Users\Administrator> (-split $aa) -join "/"
a1/a2/a3
7、下载多个文件(前提所指定的网络文件可下载)
# 下载 安装 文件
$client=new-object System.Net.WebClient
#需要下载的文件名
$installfile= "7z.dll","7z.exe","gse_client-windows-x86_64.tgz","normaliz.dll","winagent_install.zip"
#echo $installfile.Length
for($i=0; $i -lt $installfile.Length; $i++)   
{  
   # echo $installfile[$i]
    $aa=$installfile[$i]
    echo $aa
    $client.DownloadFile("http://$serverip`:$serverport/download/$aa", "C:/$aa")
 }
8、Powershell转换文本文件为ASCII编码
  1. 转换文本文件为ASCII编码
# Convert any text file to ASCII
param( [string] $infile = $(throw "Please specify a filename.") )
$outfile = "$infile.ascii"
get-content -path $infile | out-file $outfile -encoding ascii
  1. 转换文本文件为Unicode编码
# Convert any text file to Unicode
param( [string] $infile = $(throw "Please specify a filename.") )
$outfile = "$infile.unicode"
get-content -Path $infile | out-file $outfile -encoding unicode
  1. 转换文本文件为UTF-8编码
# Convert any text file to UTF-8
param( [string] $infile = $(throw "Please specify a filename.") )
$outfile = "$infile.utf8"
get-content -Path $infile | out-file $outfile -encoding utf8
9、powershell中调用bat脚本
start "C:\Windows Server NTP时间服务器配置V1.0(1)(1).bat"

好文章
https://blog.csdn.net/u010326994/article/details/72760450?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param

9.查看windows系统版本
Get-WmiObject -Class Win32_OperatingSystem | Select-Object -ExpandProperty Caption
10.删除目录(非空目录)
rm -Path "c:\RZY"  -Recurse -Force
11、判断工作组为workgroup
# 检查工作组是否为 workgroup
$Work_Group=(Get-WmiObject  Win32_ComputerSystem|findstr WORKGROUP|%{$_.split(":")[1]}|%{$_.split(" ")[1]})
if ( "$Work_Group" -eq "WORKGROUP" ) { 
    echo ""
    echo " WorkGroup is :  $Work_Group " 
    echo " WorkGroup is :  $Work_Group " > WorkGroup.txt
    echo ""
}  else {
    echo ""
    echo " Domain is :  $Work_Group  "
    echo " Domain is :  $Work_Group  " >  Domain.txt
    echo ""
}

12、执行命令屏蔽输出 (类似linux &>/dev/null)

-ErrorAction SilentlyContinue

rm -Path C:\temp  -Recurse -Force  -ErrorAction SilentlyContinue
echo aa|Out-Null
13、远程服务器上传下载文件函数

本函数用于与FTP服务器通信,上传、下载、查看文件列表

Function ftp($ftpurl,$username,$password,$do,$filename,$DownPatch) { 
# ftp 服务器地址,用户名,密码,操作(上传up/下载down/列表list),文件名,下载路径
# 示例:ftp ftp://10.10.98.91/ ftpuser shenzhen up C:\Windows\setupact.txt
    if ($do -eq "up")
    {
        $fileinf=New-Object System.Io.FileInfo("$filename")
        $upFTP = [system.net.ftpwebrequest] [system.net.webrequest]::create("$ftpurl"+$fileinf.name)
        $upFTP.Credentials = New-Object System.Net.NetworkCredential("$username","$password")
        $upFTP.Method=[system.net.WebRequestMethods+ftp]::UploadFile
        $upFTP.KeepAlive=$false
        $sourceStream = New-Object System.Io.StreamReader($fileInf.fullname)
        $fileContents = [System.Text.Encoding]::UTF8.GetBytes($sourceStream.ReadToEnd())
        $sourceStream.Close();
        $upFTP.ContentLength = $fileContents.Length;
        $requestStream = $upFTP.GetRequestStream();
        $requestStream.Write($fileContents, 0, $fileContents.Length);
        $requestStream.Close();
        $response =$upFTP.GetResponse();
        $response.StatusDescription
        $response.Close();
    }
    # 上传示例:ftp ftp://10.10.98.91/ ftpuser shenzhen up C:\Windows\setupact.txt

    if ($do -eq "down")
    {
        $downFTP = [system.net.ftpwebrequest] [system.net.webrequest]::create("$ftpurl"+"$filename")
        $downFTP.Credentials = New-Object System.Net.NetworkCredential("$username","$password")
        $response = $downFTP.getresponse()
        $stream=$response.getresponsestream()
        $buffer = new-object System.Byte[] 2048
        $outputStream=New-Object System.Io.FileStream("$DownPatch","Create")
        while(($readCount = $stream.Read($buffer, 0, 1024)) -gt 0){
            $outputStream.Write($buffer, 0, $readCount)
        }
        $outputStream.Close()
        $stream.Close()
        $response.Close() 
        if(Test-Path  $DownPatch){echo "DownLoad successful"}
    }
   #下载示例:ftp ftp://10.10.98.91/ ftpuser shenzhen dowm "setupact.txt" "C:\Windows\setupact.txt"

    if ($do -eq "list")
    {
        $listFTP = [system.net.ftpwebrequest] [system.net.webrequest]::create("$ftpurl")
        $listFTP.Credentials = New-Object System.Net.NetworkCredential("$username","$password")
        $listFTP.Method=[system.net.WebRequestMethods+ftp]::listdirectorydetails
        $response = $listFTP.getresponse()
        $stream = New-Object System.Io.StreamReader($response.getresponsestream(),[System.Text.Encoding]::UTF8)
        while(-not $stream.EndOfStream){
            $stream.ReadLine()
        }
        $stream.Close()
        $response.Close()     
    }
  #查看目录中的文件示例:ftp ftp://10.10.98.91/ ftpuser shenzhen list
}
14、获取随机数

这个随机数 与 时间有关系,每秒变化一次,频繁的取会有重复(慎用)

$check_random=cmd /c echo %random%
echo $check_random
15、while 循环
$n=1
while($n -gt 0)
{
  echo "哈哈"
  if ( 判断条件 ){ $n=0}
}
15、字符颜色
function red_echo ($red) { Write-Host ($red) -nonewline -foregroundcolor 'Red';echo ""}
function green_echo ($green) { Write-Host ($green) -nonewline -foregroundcolor 'Green';echo ""}
function yellow_echo ($yellow) { Write-Host ($yellow) -nonewline -foregroundcolor 'Yellow';echo ""}
function magenta_echo ($magenta) { Write-Host ($magenta) -nonewline -foregroundcolor 'Magenta';echo ""}
function blue_echo ($blue) { Write-Host ($blue) -nonewline -foregroundcolor 'Blue';echo ""}

green_echo "绿色"
red_echo "红色"
yellow_echo "黄色"
magenta_echo "紫色"
blue_echo "蓝色"
image.png
15、过滤大于30天的文件
ls C:\Windows\*.log | Where-Object { $_.LastWriteTime -gt [datetime]::Now.Date.AddDays(-30) }
16、多个空格变为一个空格

j解释:至少出现两次空格, “ ”中加想要替换的内容

"太多    太多的   空格 怎么才能减少 " -replace "\s{2,}" ," "
# 太多 太多的 空格 怎么才能减少
17、时间格式 Get-Date

yyyy  年
M   月
d    日
h   小时(12小时制)
H   小时(24小时制)
m   分钟
s    秒

PS C:\Users\Administrator> Get-Date

2021年3月1日 20:47:51

PS C:\Users\Administrator> Get-Date -Format 'yyyyMMddHHmmss'
20210301204804
18、自定义命令光标字符
Function Global:Prompt { "$env:USERNAME@$env:USERADMIN $PWD`n"   }
19、变更dvd驱动器盘符:

网上找了很久找都找不到, 这是一个powershell群里的大佬找到给我的,表示感谢~~

$DVD_Drive = Get-WmiObject win32_volume -filter 'DriveLetter = "D:"'  #旧盘符
$DVD_Drive.DriveLetter = "L:" # 新盘符
$DVD_Drive.Put()
20、长ping加时间戳:
ping -t  10.14.136.70 |Foreach{ "{0} - {1}" -f (Get-Date),$_}

2022/4/11 17:40:27 - 来自 10.14.136.70 的回复: 字节=32 时间<1ms TTL=61
2022/4/11 17:40:28 - 来自 10.14.136.70 的回复: 字节=32 时间<1ms TTL=61
20、传参

给脚本传递参数

方法1:直接按顺序取 $args参数
  脚本内容:
  param()
  $args[0]-$args[1]

 执行脚本:
  .\test.ps1  5 3
  2

方法2:指定变量传参
  脚本内容:
  param($a,$b)
  $a - $b

  执行脚本方式1:  不加参数,从左往右给变量匹配
  .\test 10 2
  8

  执行脚本方式2: 给每个参数指定值
  .\test  -b 8 -a 2
  -6
21、删除文件中的内容

替换的是文件全局的内容

$Path_swp="文件名"
(Get-Content $Path_swp) -Replace ',{1,}', ' ' | Set-Content $Path_swp|Out-Null    #替换"," 为 " " (空格)
(Get-Content $Path_swp) -Replace ';{1,}', ' ' | Set-Content $Path_swp|Out-Null    #替换";" 为 " " (空格)
 (Get-Content $Path_swp) -Replace '\s{1,}', "`n" | Set-Content $Path_swp|Out-Null #替换" " (空格) 为换行符 
(Get-Content $Path_swp)|?{$_.trim() -ne "" } |  Set-Content $Path_swp|Out-Null    # 删除空行,包含带空格的空行

\s 表示空格
`n 表示换行符
{1,} 表示匹配紧挨着前面字符一个以上(意思就是匹配多个相同的字符)
trim() 是一种删除包含空格但没有其他内容的行的方法

22、后台运行(作业)
  1. 后台运行命令
start-job -scriptblock{ ping 10.13.98.28}

2.使用for循环批量后台运行命令,也可以理解为并发执行

$ip_list = cat D:\aa.txt

foreach ( $n in $ip_list ) { 
echo $n
$aa = [scriptblock]::Create("ping $n -n 2000 > d:\3\${n}.txt")

$job = Start-Job -ScriptBlock  $aa 
}

3.后台运行指定的powershell脚本

 Start-Job -FilePath D:\bak.ps1 -Name my_ps

-FilePath 指定脚本的路径
-Name 本次后台作业的名称

4.查看后台运行的作业信息(查看也可以使用作业Id,Id不固定,不建议用)

PS C:\Users\aa> Get-Job my_ps
Id     Name            PSJobTypeName   State         HasMoreData     Location             Command                  
--     ----            -------------   -----         -----------     --------             -------                  
325    my_ps           BackgroundJob   Running       True            localhost            F:\工具集合\cwrsync_6.2.7_...

5.查看后台作业执行的具体命令:

PS C:\Users\aa> (Get-Job my_ps).Command

6.查看后台作业的命令执行的输出信息(就与前台执行显示的一样)

PS C:\Users\aa> Receive-Job  -name ping -Keep

-Keep 迭代输出,如果不加该参数,上次输出过的内容将不会再显示

7.删除作业

Remove-Job -Name my_ps    # 指定作业名删除作业
Remove-Job -Id Job312     # 指定作业 Id 删除作业
Get-Job| Remove-Job       #删除全部作业
23、根据文件路径获取目录、文件名
#文件路径
PS C:\Users\Administrator> (Get-Process -FileVersionInfo -Name hekad).FileName
C:\RZY\heka-1_10_0.27-windows-386\bin\hekad.exe
#获取文件所在目录
PS C:\Users\Administrator> Split-Path ((Get-Process -FileVersionInfo -Name hekad).FileName)
C:\RZY\heka-1_10_0.27-windows-386\bin
#获取文件名
PS C:\Users\Administrator> (Get-Process -FileVersionInfo -Name hekad).FileName|%{$_.split("\")[-1]}
hekad.exe
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容