Repository navigation
Expand file tree
/
Copy pathxlib.cmd
More file actions
5794 lines (5168 loc) · 225 KB
/
Copy pathxlib.cmd
File metadata and controls
5794 lines (5168 loc) · 225 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
0> /* :
@echo off
:: Copyright 2017 bin jin
::
:: Licensed under the Apache License, Version 2.0 (the "License");
:: you may not use this file except in compliance with the License.
:: You may obtain a copy of the License at
::
:: http://www.apache.org/licenses/LICENSE-2.0
::
:: Unless required by applicable law or agreed to in writing, software
:: distributed under the License is distributed on an "AS IS" BASIS,
:: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
:: See the License for the specific language governing permissions and
:: limitations under the License.
::
:: Framework:
::
:: A function whose name conforms to the specification gets:
:: External invocation. (Support short name completion)
:: Error handling.
:: Help information.
:: The functions list.
::
:: The annotation [:::] is the help text and must sit above the label it describes. For example:
:: ::: "[brief_introduction]" "" "Usage: %~n0 [function_name] [OPTION]..."
:: :[script_name_without_suffix]\[function_name]
:: [function_body]
:: :: Normal comment; [:::] is reserved for the annotation.
:: call :sub\[function_name]\%*
:: ...
:: :: Return false status.
:: exit /b 1
::
:: ::: " -o, --option=FILE [description]"
:: :sub\[function_name]\[--arg]
:: [function_body]
:: :: Exit and display [error_description_1].
:: exit /b 2 @REM [error_description_1]
::
::
:: Thread:
:: For example:
:: \\:[function_name] [args1] [args2] ...
:: ...
:: :[function_name]
:: ...
:: goto :eof
:::::::::::::::::::::
:: basic functions ::
:::::::::::::::::
:: Reset errorlevel.
set errorlevel=
:: Re-run this script by its own path when the first argument is a UNC path.
if "%~d1"=="\\" call :thread "%*" & exit
:: Add this script's directory to PATH when it is not on PATH yet.
for %%a in (%~nx0) do if "%%~$path:a"=="" set path=%path%;%~dp0
if "%~2"=="-h" call :this\annotation :%~n0\%~1 & exit /b 0
if "%~2"=="--help" call :this\annotation :%~n0\%~1 & exit /b 0
2>nul call :%~n0\%*
if not errorlevel 0 exit /b 1
:: Show the function help when the function returns an error status.
if errorlevel 1 call :this\annotation :%~n0\%* & goto :eof
exit /b 0
:::::::::::::::
:: functions ::
:::::::::::
:xlib\
:xlib\--help
:xlib\-h
call :this\annotation
exit /b 0
::: "Print version and exit" "" "Usage: %~n0 version"
:xlib\version
>&3 echo 0.26.9.26
exit /b 0
::: "Manage environment variables" "" "Usage: %~n0 var [OPTION]..." ""
:xlib\var
if "%~1"=="" call :this\annotation %0 & goto :eof
call :sub\var\%*
goto :eof
:: Override the process environment.
:: The operand is a variable name prefix; a trailing '*' matches every name that starts with it.
::: " -u, --unset=VAR unset VAR; a trailing '*' matches VAR by prefix"
:sub\var\--unset [variable_prefix_name]
:sub\var\-u
if "%~1"=="" exit /b 10 @REM The variable prefix is empty.
for /f "usebackq delims==" %%a in (`
2^>nul set %1
`) do set %%a=
exit /b 0
::: " -e, --env=KEY VALUE set the system environment variable KEY to VALUE"
:sub\var\--env
:sub\var\-e
if "%~1"=="" exit /b 22 @REM The key is empty.
if "%~2"=="" exit /b 23 @REM The value is empty.
@REM for %%a in (wmic.exe) do if "%%~$path:a"=="" exit /b 24 @REM 'wmic.exe' is not on the PATH.
for %%a in (setx.exe) do if "%%~$path:a" neq "" >nul setx.exe %~1 %2 /m & exit /b 0
@REM if defined %~1 wmic.exe environment where 'name="%~1" and username="<system>"' set VariableValue="%~2"
@REM if not defined %~1 wmic.exe environment create name="%~1",username="<system>",VariableValue="%~2"
exit /b 0
::: " -sel, --set-errorlevel=NUM set errorlevel to NUM"
:sub\var\--set-errorlevel
:sub\var\-sel
if "%~1"=="" goto :eof
exit /b %1
::: " -p, --in-path=FILE test whether FILE is found on the PATH"
:sub\var\--in-path
:sub\var\-p
if "%~1" neq "" if "%~$path:1" neq "" exit /b 0
exit /b -1
::: " -sp, --trim-path=VAR remove the empty and missing entries from the PATH-like variable VAR"
:sub\var\--trim-path
:sub\var\-sp
if "%~1"=="" exit /b 56 @REM The variable name is empty.
if not defined %~1 exit /b 57 @REM The variable name is not defined.
setlocal enabledelayedexpansion
:: TODO: get the variable value as a PATH.
:: Trim the quotes.
set _var=!%~1:"=!
:: " Trim head/tail semicolons
if "%_var:~0,1%"==";" set _var=%_var:~1%
if "%_var:~-1%"==";" set _var=%_var:~0,-1%
:: Drop the trailing backslash at the end of a directory entry.
set _var=%_var:\;=;%;
:: Delete every entry that does not exist.
call :this\path\trim "%_var:;=" "%"
endlocal & set %~1=%_var:~0,-1%
exit /b 0
:: Delete the PATH entries that do not exist, for :sub\var\--trim-path.
:this\path\trim
if "%~1"=="" exit /b 0
if not exist %1 set _var=!_var:%~1;=!
shift /1
goto %0
::: " -rp, --reset-path reset PATH to the system value"
:sub\var\--reset-path
:sub\var\-rp
call :this\cim || goto legacy\reset_path
for /f "usebackq tokens=2 delims==" %%a in (`
PowerShell.exe ^
-NoLogo ^
-NonInteractive ^
-ExecutionPolicy Unrestricted ^
-Command "(Get-CimInstance Win32_Environment -Filter \"Name='Path' and SystemVariable=True\").VariableValue"
`) do call set path=%%a
goto :eof
:legacy\reset_path
for /f "usebackq tokens=2 delims==" %%a in (`
wmic.exe ENVIRONMENT where "Caption='<SYSTEM>\\Path'" get VariableValue /format:list
`) do call set path=%%a
exit /b 0
::: " -ic, --install-config install an AutoRun hook that loads %USERPROFILE%\.batchrc"
:sub\var\--install-config
:sub\var\-ic
setlocal
call :sub\var\--backspace _bs
call :regedit\on
reg.exe ^
add "HKCU\SOFTWARE\Microsoft\Command Processor" ^
/v AutoRun ^
/t REG_SZ ^
/d "if not defined BS set BS=%_bs%&& (for /f \"usebackq delims=\" %%a in (\"%%USERPROFILE%%\.batchrc\") do @call %%a)>nul 2>&1" /f
call :regedit\off
if exist "%USERPROFILE%\.batchrc" endlocal & exit /b 0
> "%USERPROFILE%\.batchrc" (
echo ;use ^>^&3 in script can print
echo set devmgr_show_nonpresent_devices=1
echo doskey.exe which=where.exe $*
echo set path=%%path%%;%~dp0
echo,
echo title Command Prompt
)
endlocal
exit /b 0
::: " -uc, --uninstall-config remove the AutoRun hook installed by --install-config"
:sub\var\--uninstall-config
:sub\var\-uc
setlocal
call :regedit\on
@REM erase "%USERPROFILE%\.batchrc"
reg.exe delete "HKCU\SOFTWARE\Microsoft\Command Processor" /v AutoRun /f
call :regedit\off
endlocal
exit /b 0
::: "Sleep for a number of milliseconds" "" "Usage: %~n0 sleep MS"
:xlib\sleep
call :sub\is\--integer "%~1" || exit /b 22 @REM The argument is not an integer.
@REM start /min /w mshta.exe vbscript:setTimeout("window.close()",1200)
start /w MsHta.exe JavaScript:document.write();setTimeout('close()',%~1);
exit /b 0
::: "Run a command as administrator or in the background" "" "Usage: %~n0 run [OPTION]..." ""
:xlib\run
if "%~1"=="" call :this\annotation %0 & goto :eof
call :sub\run\%*
goto :eof
::: " -a, --admin[=COMMAND]... run COMMAND as the local administrator"
:sub\run\--admin
:sub\run\-a
@REM net.exe user administrator /active:yes
@REM net.exe user administrator ???
runas.exe /savecred /user:administrator "%*"
exit /b 0
::: " -q, --vbhide=COMMAND run COMMAND in the background with no window"
:sub\run\--vbhide
:sub\run\-q
if "%~1"=="" exit /b 22 @REM The command is empty.
@REM mshta.exe VBScript:CreateObject("WScript.Shell").Run("""%~1"" %~2", 0)(Window.close)
:: See the ShellExecute code snippet at https://docs.microsoft.com/zh-tw/windows/desktop/shell/shell-shellexecute#code-snippet-1.
@REM mshta.exe VBScript:CreateObject("Shell.Application").ShellExecute("%~1","%~2","","open",0)(window.close) 'No spaces are allowed in the preceding code 'e.g. "D:\demo.exe" "--config ""D:\demo 2.config"""
call :xlib\vbs vbhide "%~1"
exit /b 0
::: "Test a string or the run-time environment" "" "Usage: %~n0 is [OPTION]... [STRING]" ""
:xlib\is
if "%~1"=="" call :this\annotation %0 & goto :eof
call :sub\is\%*
goto :eof
::: " -i, --integer[=STRING] test whether STRING is an integer"
:sub\is\--integer
:sub\is\-i
if "%~1"=="" exit /b -1
setlocal
set _tmp=
:: A valid integer round-trips through 'set /a' unchanged.
2>nul set /a _code=-1, _tmp=%~1
if "%~1"=="%_tmp%" set _code=0
endlocal & exit /b %_code%
::: " --pipe test whether the script is running after a pipe"
:sub\is\--pipe
::: " --gui test whether the script is running at the GUI"
:sub\is\--gui
setlocal
set cmdcmdline=
set _cmdcmdline=%cmdcmdline:"='%
:: "
set _code=0
if /i "%0"==":sub\is\--pipe" if "%_cmdcmdline%"=="%_cmdcmdline: /S /D /c' =%" set _code=-1
if /i "%0"==":sub\is\--gui" if "%_cmdcmdline%"=="%_cmdcmdline: /c ''=%" set _code=-1
@REM if /i "%0"==":sub\is\--gui" for %%a in (%cmdcmdline%) do if /i %%~a==/c set _code=0
endlocal & exit /b %_code%
:: Test whether a string is a MAC address.
:sub\is\--MACaddr
:sub\is\-mac
setlocal enabledelayedexpansion
set "_mac_addr=%~1"
for %%z in (
%_mac_addr:|= %
) do for /f "usebackq tokens=1-6 delims=-:" %%a in (
'%%z'
) do (
if "%%z" neq "%%a-%%b-%%c-%%d-%%e-%%f" if "%%z" neq "%%a:%%b:%%c:%%d:%%e:%%f" exit /b -1
for %%g in (
"%%a" "%%b" "%%c" "%%d" "%%e" "%%f"
) do (
2>nul set /a _hx=0x%%~g || exit /b -1
if !_hx! gtr 255 exit /b -1
)
)
endlocal
exit /b 0
::: "Process tools" "" "Usage: %~n0 ps [OPTION]..." ""
:xlib\ps
call :sub\ps\%*
goto :eof
:sub\ps\
call :this\cim || goto legacy\ps
for /f "usebackq tokens=1* delims==" %%a in (`
PowerShell.exe ^
-NoLogo ^
-NonInteractive ^
-ExecutionPolicy Unrestricted ^
-Command "Get-CimInstance Win32_Process | ForEach-Object { $_ | Select-Object -Property CommandLine,Description,ProcessId | Format-List } | Out-String -Stream"
`) do if "%%~b" neq "" echo,%%b
goto :eof
:legacy\ps
for /f "usebackq tokens=1* delims==" %%a in (`
wmic.exe process get CommandLine^,Description^,ProcessId /value
`) do echo,%%b
exit /b 0
::: " -qf=FILE list the processes that use FILE"
:sub\ps\--qf
:sub\ps\-qf
if not exist "%~f1" exit /b 29 @REM The target file was not found.
fsutil.exe file queryProcessesUsing "%~f1"
goto :eof
::: " -t, --test=EXE test whether the process EXE is running"
:sub\ps\--test
:sub\ps\-t
@REM tasklist.exe /v /FI "imagename eq %~n1.exe"
if "%~1"=="" exit /b 32 @REM The process name is empty.
call :this\cim || goto legacy\ps_test
>nul 2>&1 call PowerShell.exe ^
-NoLogo ^
-NonInteractive ^
-ExecutionPolicy Unrestricted ^
-Command "Get-Process "%~n1" -ErrorAction Stop" && exit /b 0
goto skip\legacy_ps_test
:legacy\ps_test
for /f usebackq^ tokens^=2^ delims^=^=^" %%a in (`
2^>nul wmic.exe process where caption^="%~n1.exe" get commandline /value
`) do for %%b in (
%%a
) do if /i "%%~nb"=="%~n1" exit /b 0
:skip\legacy_ps_test
exit /b -1
::: " -k, --kill=PROCESS... kill the process named PROCESS"
:sub\ps\--kill
:sub\ps\-k
if "%~1"=="" exit /b 42 @REM The process name is empty.
for %%a in (
%*
) do taskkill.exe /f /im "%%~na.exe" >nul 2>nul
@REM for /f "usebackq skip=1 tokens=2 delims=," %%b in (`
@REM 2^>nul tasklist.exe /fi "imagename eq %%a" /fo csv /nh
@REM `) do for %%b in (%%a) do >nul taskkill.exe /f /pid %%~b
@REM start "" /b "%~f0" %*
@REM taskkill.exe /f /im %~1.exe
exit /b 0
::: "Time tools" "" "Usage: %~n0 time [OPTION]..." ""
:xlib\time
if "%~1"=="" call :this\annotation %0 & goto :eof
call :sub\time\%*
goto :eof
::: " -ts, --timestamp=VAR print the Unix timestamp, like 'date +%%s'"
:sub\time\--timestamp
:sub\time\-ts
if "%~1"=="" exit /b 12 @REM The variable name is empty.
setlocal
:: Win32_UTCTime = Win32_LocalTime - (Win32_TimeZone.Bias * 60)
call :this\cim || goto legacy\timestamp
for /f "usebackq tokens=1* delims==" %%a in (`
PowerShell.exe ^
-NoLogo ^
-NonInteractive ^
-ExecutionPolicy Unrestricted ^
-Command "$c=Get-CimInstance Win32_UTCTime; 'Year={0}' -f $c.Year; 'Month={0}' -f $c.Month; 'Day={0}' -f $c.Day; 'Hour={0}' -f $c.Hour; 'Minute={0}' -f $c.Minute; 'Second={0}' -f $c.Second"
`) do if "%%~b" neq "" set _%%a=%%b
goto skip\legacy_timestamp
:legacy\timestamp
for /f "usebackq tokens=1* delims==" %%a in (`
wmic.exe /namespace:\\root\cimv2 path Win32_UTCTime GET /value
`) do if "%%~b" neq "" set _%%a=%%b
:skip\legacy_timestamp
if %_Month% lss 3 set /a _Year-=1, _Month+=12
set /a _timestamp=^
(^
_Year * 365 + _Year / 4 - _Year / 100 + _Year / 400 + ^
(153 * _Month - 457) / 5 + ^
_Day - 306 - 719163 ^
) * 24 * 60 * 60 + ^
_Hour * 3600 + _Minute * 60 + _Second
endlocal & set /a %~1=%_timestamp%
goto :eof
::: " -n, --now=VAR [HEAD] [TAIL]" " set VAR to HEAD + [YYYYMMDDhhmmss] + TAIL"
:sub\time\--now
:sub\time\-n
if "%~1"=="" exit /b 12 @REM The variable name is empty.
@REM set date=
@REM set time=
@REM :: English and Chinese date formats.
@REM for /f "tokens=1-8 delims=-/:." %%a in (
@REM "%time: =%.%date: =.%"
@REM ) do if %%e gtr 1970 (
@REM set %~1=%~2%%e%%f%%g%%a%%b%%c%~3
@REM ) else if %%g gtr 1970 set %~1=%~2%%g%%e%%f%%a%%b%%c%~3
setlocal
call :this\cim || goto legacy\now
for /f "usebackq tokens=1,2 delims==+" %%a in (`
PowerShell.exe ^
-NoLogo ^
-NonInteractive ^
-ExecutionPolicy Unrestricted ^
-Command "$d=(Get-CimInstance Win32_OperatingSystem).LocalDateTime; 'LocalDateTime=' + $d.ToString('yyyyMMddHHmmss.ffffff') + $d.ToString('zzz').Replace(':','')"
`) do if "%%~b" neq "" set _%%a=%%b
goto skip\legacy_now
:legacy\now
for /f "usebackq tokens=1* delims==" %%a in (`
wmic.exe /namespace:\\root\cimv2 path Win32_OperatingSystem GET LocalDateTime /value
`) do if "%%~b" neq "" call set "_LocalDateTime=%%~b"
call set "_LocalDateTime=%_LocalDateTime:~0,17%"
:skip\legacy_now
endlocal & set %~1=%~2%_LocalDateTime:~0,17%%~3
exit /b 0
::: " -c, --calculate print the time elapsed since the previous call" "" "The option must be called before and after the timed function."
:sub\time\--calculate
:sub\time\-c
setlocal
:: 1970/01/01 - 1601/01/01 = 134774 days = 11644473600 seconds
call :this\cim || goto legacy\calculate
for /f "usebackq tokens=1* delims==" %%a in (`
PowerShell.exe ^
-NoLogo ^
-NonInteractive ^
-ExecutionPolicy Unrestricted ^
-Command "$tz=Get-CimInstance Win32_TimeZone; $ts=Get-CimInstance Win32_PerfRawData_PerfOS_System; 'Bias={0}{1}Timestamp_Sys100NS={2}' -f $tz.Bias,[char]10,$ts.Timestamp_Sys100NS"
`) do if "%%~b" neq "" set _%%a=%%b
goto skip\legacy_calculate
:legacy\calculate
for /f "usebackq tokens=1* delims==" %%a in (`
wmic.exe /namespace:\\root\cimv2 path Win32_TimeZone GET Bias /value ^&
wmic.exe /namespace:\\root\cimv2 path Win32_PerfRawData_PerfOS_System get Timestamp_Sys100NS /value
`) do if "%%~b" neq "" set _%%a=%%b
:skip\legacy_calculate
set _Timestamp_Milliseconds=%_Timestamp_Sys100NS:~0,-5%
set _Timestamp_Seconds=%_Timestamp_Milliseconds:~0,-3%
set _Milliseconds_part=%_Timestamp_Milliseconds:~-3%
for /f "usebackq delims=" %%a in (`
set /a %_Timestamp_Seconds:~0,-2% - 116444736 - _Bias * 60 / 100
`) do set _timestamp=%%a%_Timestamp_Seconds:~-2%.%_Milliseconds_part%
if defined _calculate_time (
set /a "_diff_Timestamp=(%_timestamp:~0,-4% - %_calculate_time:~0,-4%) * 1000 + (%_timestamp:~-3% - %_calculate_time:~-3%)"
set /a _Day=_diff_Timestamp / 86400000, _Hour=_diff_Timestamp %% 86400000 / 3600000, _Minute=_diff_Timestamp %% 3600000 / 60000, _Second=_diff_Timestamp %% 60000 / 1000, _Milliseconds=_diff_Timestamp %% 1000
)
if defined _calculate_time echo %_Day%d %_Hour%h %_Minute%min %_Second%s %_Milliseconds%ms
endlocal & set _calculate_time=%_timestamp%
exit /b 0
::: "Update the hosts file from the ini configuration" "" "Usage: %~n0 hosts"
:xlib\hosts
setlocal enabledelayedexpansion
:: Load the ini configuration.
call :this\load_ini hosts 1 || exit /b 2 @REM No ini file was found.
:: Get the host names from the ini map.
call :map --keys _keys 1
:: Replace every MAC address in the map with its IPv4 address.
for /f "usebackq tokens=1*" %%a in (`
call %~nx0 ip --find %_keys%
`) do if not defined _set\%%b (
call :map --put %%b %%a 1 && call :sub\str\--2col-left %%~a %%b
set _set\%%b=-
)
:: Rewrite the hosts file entries in the page buffer.
:: Parse the IPv4 address and the host names of each line.
for /f "usebackq tokens=1* delims=]" %%a in (`
type %windir%\System32\drivers\etc\hosts ^| find.exe /n /v ""
`) do for /f "usebackq tokens=1-3" %%c in (
'. %%b'
) do call :sub\ip\--test %%d && (
call :map --get %%e _value 1 && (
for %%f in (
!_value!
) do call :sub\ip\--test "%%~f" && (
set _line=%%b
call :page --put !_line:%%d=%%f!
) || call :page --put %%b
call :map --remove %%e 1
) || call :page --put %%b
) || call :page --put %%b
call :map --array _arr 1
for %%a in (
%_arr%
) do (
call :sub\ip\--test %%a && (
call :page --put %%~a !_key!
)
set _key=%%~a
)
> %windir%\System32\drivers\etc\hosts call :page --show
endlocal
goto :eof
::: "Wake on LAN" "" "Usage: %~n0 wol [OPTION]... TARGET" "TARGET...=ALIAS,HOSTIP a MAC address, a hosts alias or an IPv4 address" ""
:xlib\wol
if "%~1"=="" call :this\annotation %0 & goto :eof
setlocal enabledelayedexpansion
:: The [hosts] ini resolves a hosts alias or an IPv4 address to a MAC address.
call :this\load_ini hosts 1
set "_bcasts="
set "_targets=%*"
if /i "%~1"=="-b" goto wol\option
if /i "%~1"=="--broadcast" goto wol\option
:: Without the option the broadcast addresses are those of the subnets of the
:: default gateways, as in the bash version of this command. A machine may
:: hold more than one physical default route, so every subnet is covered.
call :this\get_route_ip _route
for %%a in (
%_route%
) do set "_bcasts=!_bcasts! %%~na.255"
if not defined _bcasts exit /b 19 @REM Cannot resolve the broadcast IPv4 address.
goto wol\wake
:wol\option
call :sub\wol\--broadcast %*
if errorlevel 1 exit /b %errorlevel%
goto wol\wake
:wol\wake
:: Wake every TARGET, which is a MAC address, a hosts alias or an IPv4 address.
set "_macs="
for %%a in (
%_targets%
) do (
set "_addrs="
call :sub\wol\--addr %%a _addrs
set "_mac="
for %%b in (
!_addrs!
) do call :sub\is\--MACaddr %%b && (
set "_mac=-"
set "_macs=!_macs! %%b"
)
if not defined _mac exit /b 30 @REM Cannot resolve the MAC address.
)
if not defined _macs exit /b 30 @REM Cannot resolve the MAC address.
call :wol "!_macs!" "!_bcasts!"
if errorlevel 1 exit /b %errorlevel%
endlocal
exit /b 0
::: " -b, --broadcast=ADDRESS,ALIAS broadcast ADDRESS for all targets"
:sub\wol\--broadcast
:sub\wol\-b
:: It writes _bcasts and _targets in the caller's scope on purpose, so no
:: setlocal is used here. The option may be written [-b ADDRESS] or
:: [--broadcast=ADDRESS], and the rest of the line holds the targets.
set "_opt=%~1"
if /i "!_opt:~0,12!"=="--broadcast=" (
set "_opt=!_opt:~12!"
set "_targets=%~2 %~3 %~4 %~5 %~6 %~7 %~8 %~9"
) else (
set "_opt=%~2"
set "_targets=%~3 %~4 %~5 %~6 %~7 %~8 %~9"
)
if "!_opt!"=="" exit /b 19 @REM Cannot resolve the broadcast IPv4 address.
if "!_targets: =!"=="" exit /b 30 @REM Cannot resolve the MAC address.
set "_addrs="
call :sub\wol\--addr !_opt! _addrs
set "_bcasts="
for %%a in (
!_addrs!
) do if not defined _bcasts call :sub\ip\--test %%a && set "_bcasts=%%~a"
if not defined _bcasts exit /b 19 @REM Cannot resolve the broadcast IPv4 address.
exit /b 0
:: Set %~2 to the MAC and IPv4 addresses that %~1 names in the [hosts] ini, from
:: a MAC address, a hosts alias or an IPv4 address. Map 1 must hold the ini; a
:: string that names nothing stands for itself.
:sub\wol\--addr
if "%~2"=="" exit /b 1
setlocal enabledelayedexpansion
set "_line=%~1"
:: By hosts alias.
call :map --get %~1 _value 1 && set "_line=!_value!"
:: By IPv4 address: the value of the alias that holds the address.
call :sub\ip\--test "%~1" && if "!_line!"=="%~1" call :sub\wol\--addr-by-ip "%~1" _line
:: The addresses of the resolved line, in the order they are written.
set "_addr="
for %%a in (
!_line:^|^= !
) do (
call :sub\ip\--test %%a && set "_addr=!_addr! %%a"
call :sub\is\--MACaddr %%a && set "_addr=!_addr! %%a"
)
if not defined _addr exit /b 1
endlocal & set "%~2=%_addr%"
exit /b 0
:: Reverse lookup the IPv4 address %~1 in the [hosts] ini and then in the hosts
:: file, which the [hosts] command updates, and set %~2 to the value of the
:: alias that holds it.
:sub\wol\--addr-by-ip
if "%~2"=="" exit /b 1
setlocal enabledelayedexpansion
set "_line="
call :map --keys _keys 1
for %%a in (
%_keys%
) do if not defined _line (
call :map --get %%~a _value 1
for %%b in (
!_value:^|^= !
) do if "%%~b"=="%~1" set "_line=!_value!"
)
if not defined _line for /f "usebackq tokens=1,*" %%a in (`
type "%windir%\System32\drivers\etc\hosts"
`) do if "%%~a"=="%~1" for %%c in (
%%b
) do if not defined _line call :map --get %%c _value 1 && set "_line=!_value!"
if not defined _line endlocal & exit /b 1
endlocal & set "%~2=%_line%"
exit /b 0
:wol
:: %~1 is the MAC address list and %~2 the broadcast address list, so one
:: PowerShell process sends every packet: starting PowerShell is the
:: dominant cost of the command, and the number of targets varies.
PowerShell.exe ^
-NoLogo ^
-NonInteractive ^
-ExecutionPolicy Unrestricted ^
-Command "& {" ^
" $bc = '%~2' -split ' ';" ^
" $head = [Byte[]] (, 0xFF * 6);" ^
" foreach ($mac in ('%~1' -split ' ')) {" ^
" if ($mac -eq '') { continue };" ^
" $mp = [Byte[]] ($head + (($mac -split '[:-]' | ForEach-Object { [Convert]::ToByte($_, 16) }) * 16));" ^
" foreach ($b in $bc) {" ^
" if ($b -eq '') { continue };" ^
" $uc = New-Object System.Net.Sockets.UdpClient($b, 9);" ^
" $uc.EnableBroadcast = $true;" ^
" $uc.Send($mp, $mp.Length) | Out-Null; $uc.Close();" ^
" }" ^
" }" ^
"}"
if errorlevel 1 exit /b 31 @REM The magic packet was not sent.
goto :eof
::: "Show or find IPv4" "" "Usage: %~n0 ip [OPTION]..." ""
:xlib\ip
if "%~1"=="" call :this\annotation %0 & goto :eof
2>nul call :sub\ip\%*
goto :eof
::: " -t, --test=STRING test whether STRING is an IPv4 address"
:sub\ip\--test
:sub\ip\-t
if "%~1"=="" exit /b 12 @REM The address is empty.
:: [WARN] 'usebackq' makes every variable global, as in :xlib\hosts.
for /f "tokens=1-4 delims=." %%a in (
"%~1"
) do (
if "%~1" neq "%%a.%%b.%%c.%%d" exit /b -1
for %%e in (
"%%a" "%%b" "%%c" "%%d"
) do (
call :sub\is\--integer %%~e || exit /b -1
if %%~e lss 0 exit /b -1
if %%~e gtr 255 exit /b -1
)
)
exit /b 0
::: " -l, --list print the local IPv4 addresses"
:sub\ip\--list
:sub\ip\-l
setlocal
:: Get the IPv4 address of the router.
call :this\get_route_ip _route
:: "
call :this\cim || goto legacy\iplist
for %%a in (
%_route%
) do for /f "usebackq" %%b in (`
PowerShell.exe ^
-NoLogo ^
-NonInteractive ^
-ExecutionPolicy Unrestricted ^
-Command "Get-CimInstance Win32_NetworkAdapterConfiguration | Where-Object { $_.IPAddress } | ForEach-Object { $_.IPAddress }"
`) do if "%%~nb"=="%%~na" echo %%b
goto skip\legacy_iplist
:legacy\iplist
for /f usebackq^ skip^=1^ tokens^=2^ delims^=^" %%b in (`
wmic.exe NicConfig get IPAddress
`) do if "%%~nb"=="%%~na" echo %%b
:skip\legacy_iplist
endlocal
exit /b 0
::: " -f, --find=[MAC,HOST]..." " search for IPv4 by MAC address or host name" ""
:sub\ip\--find
:sub\ip\-f
if "%~1"=="" exit /b 32 @REM The host name is empty.
setlocal enabledelayedexpansion
:: Load the ini sections used by the search.
call :this\load_ini sip_setting -f
call :map --get route _routes -f
call :map --get range _range -f
call :map --get exclude _excludes -f
call :map --clear -f
if not defined _range set _range=1-127
call :this\load_ini hosts -f
set _mac_addr=
for %%a in (
%*
) do (
:: Resolve the argument from the map, or keep it as given.
call :map --get %%a _arg -f && (
set "_mac_addr=!_arg: =!"
) || set _mac_addr=%%a
:: Normalize the MAC address to dash-separated form.
set "_mac_addr=!_mac_addr::=-!"
call :map --put %%a "!_mac_addr!" -t
)
if not defined _mac_addr exit /b 0
call :map --clear -f
:: Get the IPv4 address of the router.
call :this\get_route_ip _get_route_ip
for %%a in (
%_routes% %_get_route_ip%
) do if not defined _tmp\%%~na (
set _tmp\%%~na=-
set "_route=!_route! %%a"
)
call :map --keys _keys -t
:: Clear the ARP cache.
arp.exe -d
:: Scan the range for the requested MAC addresses.
for %%a in (
%_route%
) do for /l %%b in (
%_range:-=,1,%
) do (
set _tag=1
for %%c in (%_excludes%) do if "%%~na.%%b"=="%%c" set _tag=
if defined _tag call :this\thread_valve 50 cmd.exe --find
if defined _tag start /b %~nx0 \\:ip\--find %%~na.%%b %_keys%
)
:: Print the IPv4 addresses found for the requested MAC addresses.
for %%a in (
%_keys%
) do call :map --get %%~a _value -t && for %%b in (
!_value:^|^= !
) do call :sub\ip\--test %%b && call :sub\str\--2col-left %%b %%~a
endlocal
exit /b 0
:: TODO: use nbtstat to resolve the NetBIOS name cache.
:: Thread entry point for the sip scan.
:ip\--find
:: The ping may fail while the ARP lookup still succeeds.
>nul 2>nul ping.exe -n 1 -w 1 %1
setlocal enabledelayedexpansion
for /f "usebackq skip=3 tokens=1,2" %%a in (`
arp.exe -a %1
`) do for %%c in (
%*
) do call :map --get %%~c _value -t ^
&& if "!_value:%%b=!" neq "!_value!" call :sub\str\--2col-left %%a %%~c
endlocal
exit /b 0
:: Get the IPv4 address of the default gateway.
:this\get_route_ip
if "%~1"=="" exit /b 1
setlocal enabledelayedexpansion
set _gateway=
:: "
call :this\cim || goto legacy\route_ip
:: A virtual adapter - a proxy TUN (wintun), a VPN (TAP, a WAN Miniport),
:: a Hyper-V or Wi-Fi Direct adapter - holds a default route of its own,
:: but its subnet cannot reach the LAN, so only the default routes of the
:: interfaces that NDIS does not call virtual are used. The [Virtual]
:: property of [MSFT_NetAdapter] is the classification of Windows itself,
:: so it covers every form of tunnel; a route list that the filter empties
:: falls back to the plain gateway list.
for /f "usebackq" %%a in (`
PowerShell.exe ^
-NoLogo ^
-NonInteractive ^
-ExecutionPolicy Unrestricted ^
-Command "$v = @{}; Get-CimInstance -Namespace root/StandardCimv2 -ClassName MSFT_NetAdapter | ForEach-Object { $v[[int]$_.InterfaceIndex] = $_.Virtual }; $r = Get-CimInstance -Namespace root/StandardCimv2 -ClassName MSFT_NetRoute | Where-Object { $_.DestinationPrefix -eq '0.0.0.0/0' -and -not $v[[int]$_.InterfaceIndex] }; if ($r) { $r | ForEach-Object { $_.NextHop } } else { Get-CimInstance Win32_NetworkAdapterConfiguration | Where-Object { $_.DefaultIPGateway } | ForEach-Object { $_.DefaultIPGateway } }"
`) do set _gateway=!_gateway! %%a
goto skip\legacy_route_ip
:legacy\route_ip
for /f usebackq^ skip^=1^ tokens^=2^ delims^=^" %%a in (`
wmic.exe NicConfig get DefaultIPGateway
`) do set _gateway=!_gateway! %%a
:skip\legacy_route_ip
endlocal & set %1=%_gateway%
exit /b 0
::: " --forward=[LOCAL_IP:]PORT [TO_IP:]PORT" " forward an IPv4 port to a remote host"
:sub\ip\--forward
call :sub\oset\--vergeq 6.0 || exit /b 41 @REM The OS version is too low.
:: netsh.exe interface portproxy show all
if "%~2"=="" exit /b 42 @REM The arguments are invalid.
setlocal
set _local_ip=%~1
set _to_ip=%~2
for /f "usebackq tokens=1-4" %%a in (
'%_local_ip::= % %_to_ip::= %'
) do if "%%~d"=="" (
netsh.exe interface portproxy add v4tov4 listenport=%%a connectport=%%c connectaddress=%%b
) else netsh.exe interface portproxy add v4tov4 listenport=%%b listenaddress=%%a connectport=%%d connectaddress=%%c
endlocal
exit /b 0
::: "Directory tools" "" "Usage: %~n0 dir [OPTION]..." ""
:xlib\dir
if "%~1"=="" call :this\annotation %0 & goto :eof
call :sub\dir\%*
goto :eof
::: " -id, --isdir=PATH test whether PATH is a directory"
:sub\dir\--isdir
:sub\dir\-id
setlocal
set _attribute=%~a1-
:: The first attribute character is 'd' for a directory.
set _code=-1
if %_attribute:~0,1%==d set _code=0
endlocal & exit /b %_code%
::: " -il, --islink=FILE test whether FILE is a symbolic link"
:sub\dir\--islink
:sub\dir\-il
if not exist "%~f1" exit /b -1
for /f "usebackq delims=" %%a in (`
2^>nul dir /al /b "%~dp1"
`) do if "%%a"=="%~n1" exit /b 0
:: A symbolic link appears in the 'dir /al' listing of its directory.
exit /b -1
::: " -if, --isfree=DIR test whether DIR is empty"
:sub\dir\--isfree
:sub\dir\-if
call :sub\dir\--isdir "%~1" || exit /b 32 @REM The path is not a directory.
for /f usebackq"" %%a in (`
dir /a /b "%~1"
`) do exit /b -1
exit /b 0
::: " -scs=DIR enable case sensitivity for DIR"
:sub\dir\--scs
:sub\dir\-scs
fsutil.exe file setCaseSensitiveInfo "%~f1" enable
goto :eof
::: " -qcs=DIR [DEPTH]" " query the case sensitivity of DIR" " DEPTH is a recursion depth; -r queries the whole tree" ""
:sub\dir\--qcs
:sub\dir\-qcs
setlocal
set _depth=%~2
if defined _depth (
if /i "%~2"=="-r" (
set _depth=recursive
) else set _depth=recursive %~2
)
fsutil.exe file queryCaseSensitiveInfo "%~f1" %_depth%
endlocal
goto :eof
::: " -mcs, --mkcsdir[=DIR]..." " create DIR as a case-sensitive directory" ""
:sub\dir\--mkcsdir
:sub\dir\-mcs
for %%a in (%*) do mkdir "%%~fa" && >nul fsutil.exe file setCaseSensitiveInfo "%%~fa" enable
goto :eof
::: " --clean=DIR remove the empty directories under DIR"
:sub\dir\--clean
if not exist "%~1" exit /b 43 @REM The target was not found.
call :sub\dir\--isdir "%~1" || exit /b 44 @REM The target is not a directory.
if exist %windir%\system32\sort.exe (
call :dir\rdEmptyDirWithSort %1
) else call :dir\rdEmptyDir %1
goto :eof
:: For :sub\dir\--clean.
:dir\rdEmptyDir
if "%~1"=="" exit /b 0
if "%~2"=="" (
call %0 "%~dp1" .
exit /b 0
) else for /d %%a in (
%1*
) do (
2>nul rmdir "%%~a" || call %0 "%%~a\" .
call %0 "%%~a\" .
)
exit /b 0
:: For :sub\dir\--clean.
:dir\rdEmptyDirWithSort
if "%~1"=="" exit /b 2
for /f "usebackq delims=" %%a in (`
dir /ad /b /s %1 ^| sort.exe /r
`) do 2>nul rmdir "%%~a"
exit /b 0
::: " -u, --unique[=DIR] move the duplicate files of DIR to '.#Trash'"
:sub\dir\--unique
:sub\dir\-u
setlocal enabledelayedexpansion
if exist "%~1" pushd "%cd%"& chdir /d "%~1" || exit /b 54 @REM The target is not a directory.
for /d %%a in (
"%cd%\*"
) do if /i "%%~nxa" neq ".#Trash" call :dir\recursion "%%~a"
for /f "usebackq delims=" %%a in (`
dir /a-d /b "%cd%"
`) do for %%b in (
"%cd%\%%~a"
) do set /a _#\%%~zb += 1 & set _$\%%~zb.!random!!random!=%%~b
if exist "%~1" popd
for /f "usebackq tokens=1* delims==" %%a in (`
2^>nul set _#\
`) do if %%b gtr 1 for /f "usebackq tokens=1* delims==" %%c in (`
2^>nul set _$\%%~na.
`) do for /f "usebackq tokens=1,2 delims=(h" %%e in (`
certutil.exe -hashfile "%%d" sha256
`) do if "%%f"=="" call :dir\hashkey "%%~na" "%%e" "%%d"
for /f "usebackq tokens=1* delims==" %%a in (`
2^>nul set _c\
`) do if %%b gtr 1 (
echo,
echo find '%%b' duplicate file.
for /f "usebackq tokens=1* delims==" %%c in (`
2^>nul set _sh\%%~nxa.
`) do call :dir\pre8 %%~nc %%d
for /f "usebackq skip=1 tokens=1* delims==" %%c in (`
2^>nul set _sh\%%~nxa.
`) do >nul mkdir ".#Trash%%~pd"& echo !_size!,MOVE '%%~d' -^> '.#Trash%%~pd'& >nul move "%%~d" ".#Trash%%~pd"
)
endlocal
goto :eof
:dir\recursion
for /r %1 %%a in (*?*) do set /a _#\%%~za += 1 & set _$\%%~za.!random!!random!=%%~a
goto :eof
:dir\hashkey
setlocal
set _arg=%~2
set _arg=%_arg: =%.%~1
endlocal & set /a _c\%_arg% += 1 & set _sh\%_arg%.%random%%random%=%~3
goto :eof
:dir\pre8
setlocal