A basis,

1. The advantage

If you need to write a batch script for a friend, python is a great way to do this.

But you’ll need to teach him how to download and install Python, as well as install various third-party libraries, for your script to work.

And Windows10 own Powershell, do not need to download a separate compiler, suitable for programmers to the layman’s popularity.

Characteristics of 2.

Strongly typed dynamic scripting language support object-oriented support for calling system apis and.NET library code is case insensitive

3. Comments

Line comment: #

Block comments: <# and #>

4. Other

Script execution is generally disabled during initialization. Whether the script executes depends on PowerShell’s execution policy.

Unable to load the file myscript.ps1 because script execution is prohibited on this system. For more information, see "get-help about_signing".Copy the code

Right-click on the Start menu in the lower left corner, select Windows PowerShell (Administrator), and choose local signature for security reasons.

#View script execution policies
Get-ExecutionPolicy
#Change the script execution policy
Set-ExecutionPolicy RemoteSigned
Copy the code
PS C:>./ myscript.ps1 #Copy the code

Second, data type

1. The variable

$variable name = initial value. The interpreter determines the type of the variable based on the initial value assigned.

You can create variables automatically without explicitly declaring them, just remember that the variable prefix is $.

All variable names start with the dollar character $, and the rest of the characters can be any characters including digits, letters, and underscores.

PowerShell variable names are also case-insensitive.

Ls variable: # Check all occupied variables (note the colon)$num=100
$num.gettype()    Check the variable typeReturned value: IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Int32 system.valueType
$num -eq $null    # If this variable is empty, return noDel variable:num # Delete variable name without $$num -eq $null    # delete succeeded, return yes
Copy the code

2. The integer

slightly

3. The floating point

slightly

4. Other types

Note that the escape character is’ and not \

PS D:/>[char]$c="A"
PS D:/>$boolean=$true
enum fruit
{
    apple
    banana
    cherry
    durian
}
$date=get-date
Copy the code

Three, operation

1. The calculation

+, -, *, /, % plus, minus, multiply, divide remainder

++, — Increases and decreases

-and, -or, and -not are not supported

-eq, -nq, -gt, -ge, -lt, and -le are equal to, unequal, greater than, greater than, less than, or equal to. Symbols are not supported

– is whether it is

Equals(CHS.Equals(chsBak) determines equality. The string comparison can be case-sensitive or not.

"A" -eq "a"; Sensitive "A" -CEq "A"; Not sensitiveCopy the code

Determines whether a variable is of compatible type (the same type or its parent type) in the form of [type name]

$a -is [int]
$b -is [array]
$a -is [ValueType]    # inherit from the parent class
Copy the code

Condition of 2.

if($true -and $true) {
    $a=0
}
elseif($a -eq $b) {
    $a=1
}
else {
    $a=2
}
Copy the code
$a="Beijing"
switch($a){$res=" Beijing"} "Shanghai" {$res=" Shanghai"}$v=18
switch($v){{$_ - lt 10} {" less than 10} "# $_ said the current incoming variables directly write the string will be output 10 {" is equal to 10"} {$_ - gt 10} {" more than 10 "}} < # output is more than 10 # >Copy the code

3. The cycle

for

for($i=0;$i -lt 10;$i+ +)
{
    Write-Output "Hello"
}
Copy the code

while

$n=5
while($n -gt 0)
{
    $n
    $n=$n-1
}
Copy the code

do-while

Do {$n= read-host "please enter a number"}while($n -ne 0)
Copy the code

With the continue keyword, you can terminate the current loop, skip all statements following the continue, and start the next loop.

Break out of loop statements using the break keyword

Array/list

1. The weak type

#Create an array
$Nums = 2, 2
$Nums =@(1,2,3)
#Creating a continuous array
$nums=1.. 5
#Weakly typed arrays can store elements of different types
$array=1,"a",(get-date)
Copy the code

2. Strong type

If you specify an element type, you cannot insert elements of different types

[int[]] $nums=@()
Copy the code

3. Loop through the number group

for($i=0;$i -lt 5;$i{+ +)
    $a[$i]
}

foreach($n in $a) {
    $n
}

$a|foreach{The $_}Copy the code

4. Common operations

#An array of count
$num.CountEmpty arrays and element prime groups can also be created with lengths of 0 and 1, and the judgment type is array#Array slice
$num[2]
$Num hc-positie [2]# 2,3,5,7
#Reverse array
$num[($num.Count).. 0]
#Add elements
$num+="A"It cannot be deleted directly, but can be combined before and after to achieve disguised deletion#String to array
$str.ToCharArray()
Copy the code

Copy the array

Like Python, direct assignments refer to the same object, one change after another

Therefore, the Clone method should be used

$chsNew=$chs.Clone()
Copy the code

Save the execution result of a command to a variable $IPcfg=ipconfig

Each row is stored as an element in an array

Format-list can be used for any object

Check the properties and methods $list [0] | fl

Five, the function

1. The statement

#Define a functionFunction FuncName(args[]) ##Delete function
del function:FuncName
Copy the code

2. Input and output

$name=read-host Input function 
#Specify color outputWrite-host Output function -ForegroundColor White -BackgroundColor RedCopy the code

Not every application that uses PowerShell supports other colors, and not every application supports all colors.

This output method does not work for regular output results, because anything the write-host command outputs to the screen cannot be captured.

If you are executing remote commands or unattended commands (pure automation), write-host may not work as you expect.

Therefore, this command is only used for direct human interaction.

#All three instructions are of the same kindWrite -host ACB # No blank characters can be quoted write "ABC" echo "ABD"Copy the code

Write-output The basic Output process is as follows:

The write-output command sets Hello World! To put in a pipe;

There is only this string in the pipe, which goes directly to the end of the pipe, the out-default command;

The out-default command passes the object to the out-host command;

The out-host command asks PowerShell’s formatting system to format the object.

Out-host puts the formatted result set on the display

Also, when you Output multiple objects, write-host separates each object with a space and write-output separates each object with a newline

3. The parameters

The easiest way to define parameters to a function is to use the built-in $args parameter.

It can recognize any parameter. This is especially true for functions where arguments are optional.

function sayHello
{
    if($args.Count -eq 0)
    {
        "No argument!"
    }
    else
    {
        $args | foreach {"Hello,$($_)"}
    }
}
#No calls refs
sayhello

#A parameter calledsayhello "World!" # can also be written as sayhello("World!" )
#Multiparameter call
$str="it's me."Sayhello 123 "aha" $STR # If the string does not contain whitespace characters such as Spaces, Function stringContact($str1="LN",$str2="P") {return $str1+$str2}#Restricted parameter type
function subtract([int]$value1,[int]$value2)
{
    return $value1-$value2
}
Copy the code

If a function returns a value, as in other programming languages, the value, including its type information, is returned directly.

But if you encounter multiple return values, PowerShell automatically constructs all the return values into an array of objects.

You can access all the output of an array function as a return value by index, but you can also specify a return value by return statement. A Return statement returns the specified value, but also interrupts the execution of the function. Statements following a Return are ignored. By default, the function returns all output from the function as the Return value of the function, which is convenient.

But it is sometimes possible to mistake unnecessary output for a return value.

When writing a script, you may need to customize some functions that require only one return value but may add comment output lines to the function or use write-host to make the function more readable

Function Test() {write-host "Try to calculate." "3.1415926" write-host "Done."}
$value=Test
#Console output
Try to calculate.
Done.

#Test return value
$value
3.1415926
Copy the code

Six, code examples

1. Batch Word to PDF

[string]$path = "C:\Users\MrYuGoui\Desktop\ppp"The path to the Word folder that needs to be batched
[string]$savepath = "C:\Users\MrYuGoui\Desktop\ppp"# Processed PDF folder path

$wordFiles = Get-ChildItem -Path $path -include *.docx, *.doc -recurse
$objWord = New-Object -ComObject word.application
$objWord.visible = $falseforeach ($wb in $wordFiles) { [string]$filepath = Join-Path -Path $savepath -ChildPath ($wb.BaseName + ".pdf") $workbook  = $objWord.documents.open($wb.fullname) Start-Sleep -s 1 $workbook.Saved = $true "saving $filepath" $workbook.ExportAsFixedFormat($filepath, 17) $objWord.Documents.close() }$objWord.Quit()
Copy the code

2. Download the installation package in batches

It can be used to batch download common software after Windows is installed for the first time.

Including QQ, wechat, Baidu network disk, etc., the following download link may be invalid, you can replace and modify, or expand the list as required.

$downList=@(@("QQ.exe","https://down.qq.com/qqweb/PCQQ/PCQQ_EXE/PCQQ2020.exe"), @("Wechat.exe","https://dldir1.qq.com/weixin/Windows/WeChatSetup.exe"), @("Lantern.exe","https://gitlab.com/getlantern/lantern-binaries-mirror/-/raw/master/lantern-installer.exe"), @("QQyinyue.exe","https://dldir1.qq.com/music/clntupate/QQMusic_YQQWinPCDL.exe"), @("WYmail.exe","http://client.dl.126.net/pcmail/dashi/mail.exe"), @ (" WPS_Pro. Exe ", "https://wdl1.cache.wps.cn/wps/download/ep/WPS2019/WPSPro_11.8.2.8875.exe"), @ (" BaiDuWangPan. Exe ", "http://wppkg.baidupcs.com/issue/netdisk/yunguanjia/BaiduNetdisk_7.0.3.2.exe"), @ (" GitTool. Exe ", "https://github.com/git-for-windows/git/releases/download/v2.28.0.windows.1/Git-2.28.0-64-bit.exe"))foreach($each in $downList) {
    curl -o $each[0] $each[1]
}
Copy the code