This article is a mirror article of machine translation, please click here to jump to the original article.

View: 11695|Reply: 1

PowerShell Getting Started Tutorial - v0.3 version

[Copy link]
Posted on 4/19/2017 4:48:30 PM | | |


---------- Chapter 1 Windows Scripting History --------------


1 The first generation of script bats. It started with win95, win98--------- and ended around 2008. Features: Character-oriented commands, with command line and pipeline.
2 Second generation script VBS. Features: Only functions, passing values, calls.
3 Third-generation script powershell. Beginning in 2012, the command has fully evolved to object-oriented. For example, tasklist and get-process are repeated wheel features: object-oriented. Inheriting the advantages of the previous two generations of scripts.



Q: Why learn PowerShell?
A:
The missionary replied that he would study for one year and five years to BAT. Simple syntax and strong library functions!
The only one in the world that supports objects with commands on both sides of the pipeline. i.e. object-oriented command 1 | Object-oriented command 2

Windows and Linux are different:
In the PowerShell script on Win,
Support CR, LF, CRLF enter. Support multi-threading and multi-process concurrency.
It is easy to embed [Text2 sound], "Report Captain, disk is full".
Embedding a graphical interface is easy. (When, the pop-up interface asks you to enter a username, password, single select, multiple select, etc.) These are the jealousies of Linux scripts.

PowerShell is different from Python:
It's easy to use Chinese in PowerShell. Chinese script name, variable name, comment. Chinese single quotation marks, Chinese double quotation marks.
Automatically recognizes GBK, UTF8, Unicode encoding. pipeline support objects, which python scripts are jealous of.



Simple syntax example 1: The magic of powershell single and double quotation marks.
Single quotes, can be quoted with double quotation marks. And vice versa.
Single and double quotation marks can be @引用 with @''.
BAT did not work.


Missionary Narrator:
I put a lot of thought into the design of the tutorial. Didn't you read the history part of what I wrote was very [simple and rough]? History is carried by one stroke.
But since I said it, it's not nonsense, I just want students to make it clear that since win7-win2008, the [objectification] of scripts has become popular. Leads to the next chapter of object-oriented explanation.
Any PS introductory tutorial should mention the difference between character-oriented and object-oriented. It is simply appropriate to rub this topic into the history of the command line.

---------- Chapter 2 The Wonderful -------------- of Object-Oriented
What is an object, why is it object-oriented, and why is Microsoft reinforcing the wheel?

Object-oriented example 1:
Question: I eat 2.2 apples a day, how many apples do I eat in 17 days?
A:
2.2 x 17 is available. It is also possible to use i++ supported by any scripting language.
for ($i = 1; $i -lt 18; $i++)
{
        $Apple = 2.2 + $Apple
        write-host $i,$Apple
}

--------------------------------------------
As soon as the question changes, I won't tell you the number of days, only tell you,
I eat 2.2 apples a day, how many apples do I eat from January 20 to June 20, 2017?
$days = ((get-date '2017-06-20') - (get-date '2017-01-20')).days #值151


I eat 2.2 apples a day, how many apples do I eat from January 20 to June 20, 2020?
$days = ((get-date '2020-06-20') - (get-date '2020-01-20')).days #值152

for ($i=(get-date '2020-01-20'); $i -lt (get-date '2020-06-20'); $i=$i.adddays(1))
{
        $Apple = 2.2 + $Apple
        write-host $i,$Apple
}

Conclusion: With the date object, counting days, hours, etc., is simple. [for,,i++] is common, but I never thought that the number i could be date-type.

------------------------------------------



What are the advantages of object-oriented?
Before object-oriented, we only have strings and integers.
1 There is an object.
----- [Character Type]-----
The glyph has system.string, which is the most basic.
System.Text.StringBuilder memory, frequently changing, large strings

----- [Numerical type]-----
system.int32, system.int64, system.decimal, system.double, System.Numerics.BigInteger infinite integer.
Commonly used is int32, decimal.

Whether 1/3*3 is equal to 1 or 0.9999 depends on the data type.
----- [Array]-----
system.array array
system.arraylist array changes frequently, such as always rewriting, appending, or deleting, you need to use this. The speed is relatively fast.
System.Collections.Generic.HashSet deduplicate arrays. Same as python's set object.

-----【Form】-----
1 command output. For example, dir, get-process.
2. When writing scripts, we use objects and attributes to construct.

----- [Others] -----
hash tables, files, etc.



2 has attributes. Attributes are arguments and are smaller than strings. Before there are no attributes, we need to filter and filter strings with [brain-burning regular], referred to as [deduction string]. If you have attributes, you don't need it.
3 There is a way. The method is the program, the code. No need to rewrite it yourself. bat is definitely not good, there is no way, there is also a personal writing, unreliable, dare not use it.
Methods can be self-written ps functions, self-written methods in ps classes.
The method you write yourself can be temporarily [merged] into a third-party class.
The method you write yourself can be temporarily [merged] into the .net class.

What are the disadvantages of object-oriented?
The preacher is teaching powershell to people who use winxp. The person said that powershell is not good, the object is too memory-intensive, and he is right.
In cmd I return 100 filenames (strings) with dir. In PowerShell, I use dir to return 100 file objects, and Powershell takes up a lot of memory.
But now is different:
1. Unnecessary content should not exist in variables. Or destroy it immediately after use to reduce memory usage.
2. The memory drop is enough. Because CPU performance can no longer go up, we are frantically increasing memory in an attempt to exchange space for time.
3. We want more powerful features, and object-orientation is the most basic these days. Which is not object-oriented, py, php, java, .net, c++?

Summary:
1 Objects are larger and more memory-intensive than strings.
2. There are more methods for object-orientation and stronger functions.
3 attributes are smaller than string granularity, which is extremely convenient to use. Avoided the [crazy use of brain-burning regular to filter] strings!


=== Crazy use of brain-burning regulars to filter examples, bat version of ping default gateway ===
@echo off&setlocal enabledelayedexpansion
echo is looking for the default gateway...

for /f "usebackq delims=" %%i in (`ipconfig /all`) do (
echo %%i|find /i "gateway">nul|| echo %%i|find "default gateway" >nul
if "!errorlevel!" =="0" (
for /f "tokens=2 delims=:" %%a in ("%%i") do for /f "delims= " %%m in ("%%a") do set ipgate=%%m
)
)

The echo default gateway is: !ipgate!
=========== ping the default gateway.ps1============
$default gateway = (get-netroute -DestinationPrefix 0.0.0.0/0). NextHop
& ping.exe $ Default Gateway

# test-connection $ default gateway
=======================






Q: Even if object-oriented is so good, where do these objects come from?
A: From the .net library.


---------- Chapter 3 Introduction to .NET --------------


Q: How many version branches does .NET Core have?
A:
There are currently three versions.
.NET 2.0 The latest version of .NET 3.51
.NET 4.0 The latest version of .NET 4.70
.NET Core 1.x The latest version of .NET 1.2 for Apple systems, Linux systems, and embedded systems.
.NET Core 2.x The latest version of .NET 2.0 for Apple systems, Linux systems, and embedded systems.



Q: How many functional branches does .net have?
A:
Desktop branch in .NET. WinForm. For developing desktop windows.
Sound library
asp.net in .NET and .NET Core. Web server function library. Used to open a B/S web server.
F# in .NET and .NET Core. Contains math libraries, trigonometric function libraries, etc.
PowerShell in .NET and .NET Core. Contains common system management interfaces such as script files.
Linux
◦Ubuntu 14.04 \ 16.04
◦CentOS/RHEL 7 and above
◦open SUSE 42 and above
◦Arch Linux (archl inux does not have a version number)
◦LINUX docker container
◦Linux AppImage container (portable application single binary) https://github.com/probonopd/AppImageKit



MAC OS X
◦OS X 10.11


Q: How does a .NET program (C# program) connect to a MySQL server?
A:
Go to the mysql official website to download the connector for .NET language.
mysql-connector-net-6.9.9-noinstall.zip--->v4.5--->MySql.Data.dll
Add the MySql.Data class to .net and add the database interface.



Conclusion:
WinXP machine first install .net 3.51, win7 and win2008 machine, first install .net 4.62 or above.

.net has been around for many years, and there are not many software that supports .net than java. All .net branches, interfaces (databases, WeChat, etc.). )
Those dlls, those libraries, powershell can be called. It is exactly the same as the exe written in C#.


Q: In addition to the .NET branch interface, what are PowerShell's own libraries (modules)?
A:
Please see the next chapter

---------- Chapter 4 Commonly Used Built-in Libraries, External Libraries, and Third-Party Libraries in PowerShell --------------

Missionary help:
This chapter cannot be discussed, but it is just a list of libraries and manuals. Bookmark this chapter. After looking at these libraries, you will know what PowerShell can do.



win2012 manual address: (most commonly used ad module)
https://technet.microsoft.com/zh-cn/library/dn249523(v=wps.630).aspx
AD User Group Management, DHCP, DNS, Printer, File Sharing, IIS, Disk, NIC,



exchange2016
https://technet.microsoft.com/zh-cn/library/bb124413.aspx
Active Directory 12         
Anti-Spam and Anti-Malware 59  
Client access 100
Extension Agent 4
Email Addresses and Address Books 37
Federation and hybrid configuration  
High availability  
Mail flow  
Mailbox  
Mailbox database  
Mailbox server  
Move and migrate  
organization  
Permissions  
Policy and compliance  
Security  
Server health, monitoring, and performance  
Share and collaborate  
Unified Message  
Users and groups  



sqlserver2016
https://msdn.microsoft.com/zh-cn/library/hh245198.aspx



lync2015
https://technet.microsoft.com/zh-CN/library/gg398867.aspx




SharePoint2016
https://technet.microsoft.com/zh-cn/library/ff678226(v=office.16).aspx



Amazon Virtual Machines, AWS, Microsoft Virtual Machines, Azure, Hyper-V, VMware vSphere, and enterprise-grade virtual machines.


Clients:
Services, processes, logs, registries, file directories, remote management. Timed tasks.



Internet:
FTP, mail, SSH client plug-in for Linux server connection.


Text:
XML, HTML, CVS, JSON, EXCEL, etc.


Text 2 voice


Graphical interface.


Microsoft Scripting Center
https://gallery.technet.microsoft.com/scrip{过滤}tcenter/


PowerShell software source official website --- official PowerShell library.
https://www.powershellgallery.com


The other Niu x libraries are all on github. In addition, the missionaries regularly publish the [Niu x Magic Weapon] of [Hidden Foot Pavilion], which is a useful third-party library of PowerShell.


---------- Chapter 5 Beginners must learn how to help the use of commands--------------


Q: How do I know the PowerShell version?
A:
$PSVersionTable



Q: I don't know the module, how to find it?
A:
get-module -ListAvailable


Q: How do I find commands when I only know part of them?
A:
get-command  *service*



Q: I know the command, but I don't know what parameters are in the command, how to list the parameters?
A:
get-help write-host -Parameter *
show-command write-host


Q: I know the parameter, but I don't know which command has this parameter, how do I find the command?
A:
get-command -ParameterName encoding



Q: How do I get help with a command from the command line?
A:
get-help get-date

-Examples command examples
-online online manual




Q: I don't know the attribute method of the command (I don't know the object), how to find it?
A:
"abc"  | get-member
get-date | get-member



Q: Where is the Chinese .NET manual?
A:
msdn。 The most basic string properties and methods are in the manual.
https://msdn.microsoft.com/zh-cn/library/system.string.aspx



---------- Chapter 6 Introduction to Common Commands --------------

The first command to learn is dir
Q: Why use powershell dir [i.e., Get-ChildItem] instead of cmd dir?
A:
Object-oriented, strong method, and many attributes.
$file = dir a:\pscode\temp183\aaa.txt
$file. FullName #返回全路径属性
$file. BaseName #返回文件名属性
$file. Extension #返回扩展名属性
$file. LastWriteTime #返回最后写入时间属性



The first syntax to learn is array syntax. $a = @(xxx command)
Q: Sometimes you have to use [character-based external commands] to divide the return values into arrays by behavior units.
A:
$a = @(ipconfig)
$a[8] #第9行


get-childitem usage:
Added parameters in PowerShell 3.0 and above

get-childitem d:\xxx -file #过滤, only output files
-Directory filtering, output only directories
-Hidden filtering, only output hidden


Q: Open a file, segment by behavior, put into an array?
A:
$a = Get-Content a:\pscode\temp183\aaa.txt -ReadCount 0



Q: Open a file, as a large string, and store the whole variable?
A:
$a = Get-Content a:\pscode\temp183\aaa.txt -raw


$a,$b,$c = 1,2,3


Q: How do I run commands in the background?
A:
There is a cmd /c "command" in ancient times.
Now there is powershell /c "command", or powershell -c "command",
powershell -file "script.ps1" -argument 1 aaaa -parameter 2 1234
start-process -path xxx.exe -ArgumentList '-parameter1 aaaa -parameter2 1234'


Q: I want to run the script with another local user, but powershell doesn't have runas. exe similar commands?
A:
There are various sessions in PowerShell.
ip + port + username + password = a session, I only need to change the username, change the password, and you can change the permissions. Because permissions are tied to the user.
Similarly, I only need to create n sessions to use, without switching users.
The most important new-pssession has the -Credential parameter, enter the user password, which is not the same as runas. Is exe the same? What else is SmbSession?
So I don't think it's necessary to use runas in powershell. exe。
You just need to use those commands with session and Credential, right?

Check the commands with the name [Credential] in the parameter name:
get-command -ParameterName Credential

View commands with the [session] character in the command:
get-command *session*


Q: How do I send an email using PowerShell?
A:
Send-MailMessage -Subject 'Subject'
-From "your hotmail account @hotmail.com" -To "your QQ email @qq.com" '
-SmtpServer "smtp.live.com" -port 587 -useSsl -credential "your hotmail account @hotmail.com" '
-Attachments $Attachments -BodyAsHTML -body $HTML the content of the email

Note:
1 usexxx@QQ.com+ Your QQ password + the above command Sending an email is not working. Because for the security of QQ passwords, Tencent requires independent email passwords.  
2 Sending from QQ mailbox is not possible by default. It is turned off, and you need to turn on SMTP in the settings.
3 PowerShell 3.0 and above only support port parameters. For win7, you need to install the latest version of PS first




Q: Monitor win CPU, disk, network, IO, etc.
A:
Performance Monitor or
Get-Counter fetches performance counter data from both local and remote computers.

Q: How can I see what counter items are available?
A:
It's all in the manual.
Check what are the main categories of uses:
Get-Counter -ListSet * | Sort-Object CounterSetName | Format-Table CounterSetName


For example, I now know that the disk category is (PhysicalDisk), and then check the subcategories in the disk, use:
(Get-Counter -ListSet PhysicalDisk). Paths




Q: How do I view the logs?
A:
Event Viewer, or
get-eventlog



Q: How do I execute strings?
A:
$cmd1 = 'xxxx'
Invoke-Expression $cmd1


Well, we've learned a lot about individual commands, let's take a look at the execution of Powershell scripts.


---------- Chapter 7 PS1 Scripting, Debugging, and Running --------------
A script is a combination and overlay of command statements. The script is glue, go around looking for others to call, look around for wheels to assemble the car. Instead of making wheels, for others to use.



Cainiao asked: How to write a script?
The old bird answered:
1 The details of the problem must be clarified. For example: make mooncakes.
2 The problem-solving ideas are also basically completed. Flour and water, put the filling, steam.
3 What commands and variables to use. Add five kernels, put them in a mold, and squeeze.
4 Write roughly first, write roughly.
5 Debugging passed.
6 Write in detail. Consider the error situation, plus the error code, the error message. Remove error-prone code that is not easily compatible. Rewrite code that doesn't perform well.
Up to this point, a good script may not look good, but it should be very useful.
7 Finely crafted. Refactoring, writing reused code snippets into functions. Rewrite variable names so that people can understand them at a glance. Format the code well and do the indentation.


Q: What IDE is used to write PS1?
A:
The most recommended is to use Visual Studio Code, plus the PowerShell plug-in.
Features: Code prompts, autocomplete, code formatting, indentation to choose space or tab, file encoding settings.
There is a plugin called FTP-sync, which can write PS1 scripts in Win's VSCode and automatically synchronize them to the Linux directory when saved.



Q: What tools are used to debug PS1?
A:
The most recommended powergui life does not use a locomotive, even if it is a hero, the PS script will also jump and report an error!
vscode is also fine



Q: What tools do you use for code formatting?
A:
Everything that should be indented is indented, and the equal signs are aligned.

PowerShell ISE + ISE Plugin [ISESteroids]

Installation:
Install-Module -Name ISESteroids

ISE runs:
Start-Steroids





Q: What tools do you use to make the code color beautiful?
A:
1 Use the above tools to format the code.
2 Use PowerShellise + Missionary DIY Color Matching 2016 Edition.
3 Grab the picture. The world's most pleasing and beautifully colored PowerShell code is produced.

All of the above IDEs are in Chinese.




Q: How do I name a script? xxx.ps1
A:
It is recommended to start with 1---2 letters, and use the Chinese file name for the rest. i.e. [bf backup all old files_ and delete .ps1 from 10 days ago]
In this way, type [bf] first, and then hit tab to complete the script name.




Q: How do I enable the PowerShell script execution permission?
A:
echo The following code can be run in cmd with administrator privileges or in PowerShell with administrator privileges.
echo if using PowerShell Remoting remote. Both the local machine and the remote machine must be run with administrator privileges.
"C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe" -command "Set-ExecutionPolicy -ExecutionPolicy Unrestricted"
"C:\WINDOWS\syswow64\windowspowershell\v1.0\powershell.exe" -command "Set-ExecutionPolicy -ExecutionPolicy Unrestricted"
& "C:\WINDOWS\system32\windowspowershell\v1.0\powershell.exe" -command "Set-ExecutionPolicy -ExecutionPolicy Unrestricted"
& "C:\WINDOWS\syswow64\windowspowershell\v1.0\powershell.exe" -command "Set-ExecutionPolicy -ExecutionPolicy Unrestricted"
pause



Q: What are the disadvantages of the locomotive (powergui)?
A:
Unable to set background color.




Q: What are the disadvantages of vscode?
A:
$ and variable name are not the same color.
Debugging functions are slow and sometimes deadlocked.




Q: What are the disadvantages of ISE?
A:
You cannot choose to save or convert the encoding.
Indent to [space], [tab] both. In other text editing software, indentation is displayed.




---------- Chapter 8 Actual Combat Drill --------------
The group 6504748 and wrote this part by themselves.

5. Example 1: Turn the service on and off
6. Example 2: Control Firewall (Open, Close, Rule)
7. Example 3: Set a policy (password policy as an example)



---------- Chapter 9 These Additional Elective Courses Are You Interested? --------------
PowerShell script, command line arguments pass values, and bind variables examples
http://www.cnblogs.com/piapia/p/5910255.html




Let powershell run only one script at a time (process mutual exclusion example)
http://www.cnblogs.com/piapia/p/5647205.html



powershell character interface, powershell plus WPF interface, 2048 game
http://www.cnblogs.com/piapia/p/5531945.html


Two crawlers in PowerShell
http://www.cnblogs.com/piapia/p/5367556.html



PowerShell script: Random password generator
http://www.cnblogs.com/piapia/p/5184114.html



Example of a PowerShell recursive algorithm
http://www.cnblogs.com/piapia/archive/2013/01/29/2881011.html



PowerShell Voice Calculator
http://www.cnblogs.com/piapia/archive/2012/10/20/2731506.html



1 List all EFS encrypted files. 2Decrypt all EFS encrypted files
http://www.cnblogs.com/piapia/p/4702514.html
It is a tool written for system administrators and network administrators.
After an employee leaves his job, his disk assumes that there are 10,000 files (directories), of which there are 3 file directories encrypted by EFS. In Explorer, these three files are green.
But if you click on (10,000 catalogs) one by one, whether it is green or not, you will be exhausted.
At this time, the network administrator uses the employee's WIN account, logs in to the employee's PC, and uses this script to list all EFS encrypted files.


---------- Chapter 10 Please Ask a Question--------------
Ladies and gentlemen, if there is something to report, leave the court without anything.



----------Chapter 11 Linux Chapter--------------

Missionary: As long as you can install the Linux version of PowerShell, you only need ps1 scripts, no sh scripts.
Interpretation:
1 In short, bash only has syntax, no commands and libraries.
2 bash only has 1% syntax functions, powershell cannot implement it. This is normal, no two leaves are exactly the same in the world.
This means you only need the ps1 script, no sh.
3 bash is too old, the same function, Powershell can be implemented, and it can also save time, such as 10,000 empty fors, Powershell needs to save 90% of the time.
4 Learn to use /usr/bin/powershell instead of /usr/bin/bash. Other Linux commands, pipelines, old kung fu, etc., are used exactly the same as in bash.
5 Gradually use object-oriented, simple and powerful PowerShell commands and libraries instead of brain-burning Linux commands, or both. ---This is the general principle, the general outline.


Q: Which versions of Linux can install PowerShell?
A:
◦Ubuntu 14.04 / 16.04
◦CentOS/RHEL 7 and above
◦open SUSE 42 and above
◦Arch Linux (archl inux does not have a version number)
◦LINUX docker container
◦Linux AppImage container (portable application single binary) https://github.com/probonopd/AppImageKit





Q: Why is it said that the command line of win is stronger than linux?
A:
Commands in 1 win have evolved into object-oriented PowerShell. Linux is not working yet. From win7 to win2012r2, the evolution ends.

2 I used to hear that Unix has many Linux commands and is very powerful. But now I'm telling you that powershell commands are at least ten times more than linux commands. Anyway, I haven't learned all my life anyway.

3 Linux is more graph-dependent, with too few commands. And the win command is much more than linux.
3.1 In any linux, the commands in the mail server are more and more complete than exchange? More convenient than exchange?
3.2 The DNS server bind of Linux is not as convenient as the DNS command of win. Does bind have a [command] to add an ipv4 A record to a domain name? Not yet dependent on web graphics?
Some people say to use nsupdate. That's not about making a text and then running the text. What is the difference between replacing the [DNS zone file] with sed and then reloading the [dns zone]?

4 In the new version of win, or in powershell, it is all [command + parameter]. And most of Linux is still [sed text].
4.1 Take the IP address assigned to the network card as an example.
nmcli connection add type ethernet con-name NEW_STATIC ifname eno1234567 ip4 192.168.1.111 gw4 192.168.1.1,
Isn't it more convenient than using sed to scrape the ifcfg-eth0 file?

5 Any language processes data, and so does scripting. With the help of objects, PowerShell is more convenient than awk. Shenma csv, excel, xml, json
sql table, nosql table. html, etc.




Q: How does PowerShell implement [sed -i "s/what to look for/replace with /g" filename]?
A:
@(Get-Content filename) -replace 'aaa','bbb' | Set-Content filename $aaa
That is, open the file, replace it, save the file.



Q: Why are fewer and fewer people using SED in Linux?
A:
Argument 1: AWK can replace SED, but SED cannot replace AWK.
sed, that is, simply find the substitution. awk has for and the like to implement complex processing.

Argument 2: AWK uses the standard regular, and the regular of sed is the same as that of sed, but the parts are different.
Learning SED means that two sets of incompatible regular standards in the brain are fighting each other.



Q: So it's right to learn AWK?
A:
Learning PowerShell is easier than learning AWK.
PowerShell uses [split and then split], [if and if], where-object, string.substing(), string[-3], etc.
Break down the string problem layer by layer. Simpler than awk regular.




Q: Can pipelines and AWK be used in PowerShell?
A:
You can call awk in PowerShell, exactly the same as in Bash. The old martial arts are completely Turin.



Q: How to implement the [awk '{print $3}'] function in PowerShell?
A:
($line -split "\s+|\t+") [0] #第一行
($line -split "\s+|\t+") [2] #第三行       

Get-Content /xxx/yyy.txt | foreach-object {$_.split()[2]}    #awk '{print $3}'


Q: How to implement the [awk -f a.awk file] function using PowerShell?
A:
Essentially, this is a filtering function that uses a pipe. In PowerShell, this is called a filter or filter.
PowerShell supports the combination of command + pipe + filter. As in Command 1 | Filter 1 | Command 2 | Filter 2 | Filter 3
filter filter1
{
AWK-like functionality
}





Q: Is there [xargs] in PowerShell?
A:
The pipe variable used in the pipeline is called [$psitem], and its alias is [$_].
PowerShell uses foreach-object and $_ to implement the function of xargs.





Q: Is there a [<] [<<] number in PowerShell?
A:
No.
Perhaps the [<] symbol from right to left is anti-human thinking. Many commands in PowerShell have been changed to left to right.
If get-random < (1..100) is not legal in PowerShell, the legal one should be get-random -inputobject (1..100), or 1. 100 |get-random
Less than 1% of strange commands [must] rely on the [<] symbol, which can be achieved by calling cmd in PowerShell or bash (PowerShell for Linux) in PowerShell.
For example, $a = bash -x "command 1 < command 2" #linux
For example, $a = cmd -c "command 1 < command 2" #cmd




Q: Is there an expect command in PowerShell? How to connect to a Linux SSH server from Win with PowerShell?
A:
1. Yes. For some strange and partial door response needs, there are third-party modules.
2 No. PowerShell does not use the expect command, but uses a session.

Use Powershell + SSH client library + IP + port + username + password to combine into a connection and send commands to this connection. The code is as follows:
$connection1 = New-SSHSession -ComputerName 1.1.1.1 -Port 22 -Credential aaaa #将提示输入密码
$to return = Invoke-SSHCommand -Command {cat /etc/issue} -SSHSession $Connection1

This standard functionality such as (MongoDB, mysql, ssh, ftp, http, telnet, etc.) has drivers or modules. ps and. .netprogram, through the driver connection, send commands, and accept data.
The benefits of using modules or drivers to send and receive [data] are:
The data will be converted into a .net object, which in turn will be converted into a PS object. Otherwise, it's all strings, and the [object-oriented martial arts] of the PS sect are all useless.


Taking MongoDB as an example, what are the advantages of using modules or drivers to send commands? Who talks?
I feel that the benefits are:
1 Multithreading. The background thread runs and does not occupy the current thread.
2. We can [disconnect halfway] from the session at any time, execute other PS code, functions, and [return to the session at any time]. Scripts are more flexible to write and easy to debug.
3session brings multiple users, and different users can have different server permissions.




Q: Is there su, runas command in powershell? How to run another user's command with PowerShell?
A:
No.
In PowerShell, running Linux native commands and pipelines is effortless. For example:
sshaaa@127.0.0.1"Executed with user AAA privileges, command xxx"  
sshpass -p user_password sshaaa@192.168.1.1



Q: Two Linux machines with SSHD? How to connect and send commands with powershell?
A:
In addition to the above method, you can also use the method of creating a new Linux session. (Connected from linux to another SSHD)
Note: This method requires editing the /etc/ssh/sshd_config file. Add the following line
Subsystem powershell powershell -sshs -NoLogo -NoProfile
After that, restart the SSHD server.
The detailed manual is here:
https://github.com/PowerShell/PowerShell/tree/master/demos/SSHRemoting

Command:
$connect2 = New-PSSession -HostName 127.0.0.1 -UserName user006 #手动输入密码或用-KeyFilePath option
invoke-command -session $connect2 -scrip{filter}tBlock {new-item ~/ccc.txt}


Summary:
Win client, connected to Linux server. Currently, third-party modules are required, of course, this is a module in the official library, just use install-module PoshSSH.
Linux client, connected to Linux server. You need to edit the /etc/ssh/sshd_config file.
Linux client, connected to Win server. You need to turn on the service on the server. Trust the server on the client.
Win client, connected to Win server. You need to turn on the service on the server. Trust the server on the client.


Q: Is there [grep] in PowerShell?
A:
The select-string command is used in powershell.
From a coding point of view alone, select-string=smart, grep=stupid + have a hard flaw :mrgreen:
When there is a BOM header, select-string automatically recognizes the file encoding type.
When there is no BOM header, there is no need to change the shell environment like linux+grep, and there is no need to save files according to a certain code. You only need to specify the -encoding parameter according to the file encoding.
And grep does not have this function, that is, there is a hard flaw of [unable to specify file encoding type].
Of course, grep is not useless, grep has some parameters, has additional unique functions, select-string does not, this is where grep is stronger than select-string.



Q: Is there an [eval] in PowerShell?
A:
Use Invoke-Expression to execute strings in powershell.



Q: Is there a tail -f in PowerShell? It is possible to output the newly generated lines of a file in real time.
A:
Get-Content D:\a.txt -Tail 10 -ReadCount 0 -Wait



Q: I want to use a small keyboard and also want a 256-color terminal, so how should xshell be set up?
A:
Terminal --- Terminal Type --- [putty-256color] or [export TERM=putty-256color]
Terminal --- Keyboard --- default or Linux.

Eterm-256color can
gnome-256color does not work
konsole-256color does not work
putty-256color
PowerShell Missionary Original Share 2017-02-15
RXVT-256COLOR doesn't work
screen-256color doesn't work
ST-256COLOR
VTE-256COLOR does not work
xterm-256color doesn't work
The same principle applies to SecureCRT




Q: Who is more powerful, shell or python?
A:
Each has its own strengths and can complement each other. But they are not complementary. More on this below.


Q: Why is the Linux version of PowerShell more suitable for operation and maintenance personnel to write scripts? (Compared to Linux version of Python)
A:
1 Python has object-oriented functions, and the Linux version of PowerShell is available.

2 python does not have a command line.
2.1 Python cannot be the default terminal for SSH, but PowerShell for Linux can. See the chapter: "Two Linux Machines with SSHD? How to connect and send commands with powershell? 》
2.2 Using shell commands (awk, grep, etc.) in python is very cumbersome. Need to add a lot of py syntax and code. PowerShell for Linux runs the awk commands just like bash.

3 python has no pipes. It is very troublesome to pass values between n [command line programs]. Need to add a lot of py syntax and code. The Linux version of PowerShell has pipelines, and running awk commands is the same as bash.

4 python has version 2, version 3 is not compatible with cancer! Question. PowerShell for Linux doesn't have such a problem.
4.1 These questions contain coding problems.

Conclusion:
shell commands such as grep are not good for coding support, not as good as the coding problems of 4.1 above in PowerShell at home. Plus the above 2,3 points.
It makes Linux people feel uncomfortable, but very few people use external commands in py. [py command library] and [shell command] are dead and basically cannot complement each other. The Linux version of PS is different.




Q: Why is it said that powershell is better than shell?
A:
1 PowerShell is object-oriented, and properties return directly available data. This is much less common than in character scripting languages (bat, shell) that require string deductions.
Born with less [content that needs to be escaped].
2 String search substitution, there are methods in PowerShell that do not require escaping, in the .NET class. For example:
[string]$a = 'abc\\def'
$b = $a.replace('\\','when')
#返回: [ABC as def]
To determine whether an IP is legitimate, you can use the TryParse() method in the IPAddress class.
In short, my suggestion is to use as many .net methods as possible, use as little regex as possible, or just use simple regulars.
3 PowerShell uses ['] as an escape symbol. ['] is less commonly used than [\] and is much less used as an escape symbol.
3.1 When writing database scripts, there are more conflicts of ['].
For example, ['table'] will conflict with ['t], such as ['biao'] will conflict with ['b], and I later solved it with ['table'].
4 ps string search and replacement, has a regular engine, is compatible with Linux, and also uses [\] as an escape.
However, there is a special string escape function [[Regex]::Escape()], which is escaped first and then found and replaced, and the code is highly readable.
$Original string before escape = '\+\&*|]'
$escaped string = [regex]::escape($original string before escaping)
-------------
Script examples
[string]$a = 'abc\\def'
$Original string before escape = '\'
$Escaped String = [Regex]::Escape($Original String Before Escape) #[\]--->[\\]
$b = [Regex]::replace($a,$Escaped String, 'When')
$b #返回 [ABC Dangdang DEF]
-------------
5 bash and awk, each has its own for, each has its own escape. Combined, it is easy for A to affect B, and A swallows B.
It is also easy to have problems when encountering ['], ["], [\], and [*].
It's like wearing two layers of long pants, you pull one layer, and the other layer also moves, you need to worry about their compatibility.
This is cancer and difficult to solve.
But pinch, this problem can also be avoided to a certain extent. This requires the person who wrote the shell to correct the stinky problem.
[Put the awk code in the .awk file separately, not on the command line]
powershell does not have this problem, put it on the command line, put it in the script, it has no effect.








Previous:.net/C# uses Attributes to implement simple AOP
Next:.net/c# Speedy IP Open Port Scanner v2.0 Ultimate Version
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com