美文网首页
windows powershell 命令 持续更新

windows powershell 命令 持续更新

作者: 木头_95b3 | 来源:发表于2020-06-29 14:27 被阅读0次
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 }
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
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

相关文章

网友评论

      本文标题:windows powershell 命令 持续更新

      本文链接:https://www.haomeiwen.com/subject/frrcxktx.html