forked from lukesampson/psutils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
getopt.ps1
71 lines (62 loc) · 1.74 KB
/
getopt.ps1
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
# adapted from http://hg.python.org/cpython/file/2.7/Lib/getopt.py
# argv:
# array of arguments
# shortopts:
# string of single-letter options. options that take a parameter
# should be follow by ':'
# longopts:
# array of strings that are long-form options. options that take
# a parameter should end with '='
# returns @(opts hash, rem_args array, error string)
function getopt($argv, $shortopts, $longopts) {
Set-StrictMode -Off;
$opts = @{}; $rem = @()
function err($msg) {
$opts, $rem, $msg
}
# ensure these are arrays
$argv = @($argv)
$longopts = @($longopts)
for($i = 0; $i -lt $argv.length; $i++) {
$arg = $argv[$i]
# don't try to parse object arguments
if($arg -is [array]) { $rem += ,$arg; continue }
if($arg -is [int]) { $rem += $arg; continue }
if($arg.startswith('--')) {
$name = $arg.substring(2)
$longopt = $longopts | ? { $_ -match "^$name=?$" }
if($longopt) {
if($longopt.endswith('=')) { # requires arg
if($i -eq $argv.length - 1) {
return err "option --$name requires an argument"
}
$opts.$name = $argv[++$i]
} else {
$opts.$name = $true
}
} else {
return err "option --$name not recognized"
}
} elseif($arg.startswith('-') -and $arg -ne '-') {
for($j = 1; $j -lt $arg.length; $j++) {
$letter = $arg[$j].tostring()
if($shortopts -match "$letter`:?") {
$shortopt = $matches[0]
if($shortopt[1] -eq ':') {
if($j -ne $arg.length -1 -or $i -eq $argv.length - 1) {
return err "option -$letter requires an argument"
}
$opts.$letter = $argv[++$i]
} else {
$opts.$letter = $true
}
} else {
return err "option -$letter not recognized"
}
}
} else {
$rem += $arg
}
}
$opts, $rem
}