Repository navigation
Expand file tree
/
Copy pathwinrm.py
More file actions
696 lines (601 loc) · 24.8 KB
/
Copy pathwinrm.py
File metadata and controls
696 lines (601 loc) · 24.8 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
#!/usr/bin/env python3
# -*- coding: utf-8; py-indent-offset: 4 -*-
#
# Author: Linuxfabrik GmbH, Zurich, Switzerland
# Contact: info (at) linuxfabrik (dot) ch
# https://www.linuxfabrik.ch/
# License: The Unlicense, see LICENSE file.
# https://github.com/Linuxfabrik/lib/blob/main/CONTRIBUTING.md
"""This library collects some Microsoft WinRM related functions."""
__author__ = 'Linuxfabrik GmbH, Zurich/Switzerland'
__version__ = '2026102403'
import base64
import re
import threading
import warnings
try:
import winrm
HAVE_WINRM = True
except ImportError:
HAVE_WINRM = False
try:
from pypsrp.client import Client
HAVE_JEA = True
except ImportError:
HAVE_JEA = False
from . import txt
_AUTH_MAP = {
'kerberos': 'kerberos',
'negotiate': 'negotiate',
'ntlm': 'ntlm',
'credssp': 'credssp',
'basic': 'basic',
'plaintext': 'basic',
'ssl': 'basic',
}
def _build_auth(args):
"""
Build a `(username, password)` tuple from `args`.
For Kerberos/negotiate transports with missing credentials,
returns `(None, None)` so the library falls back to the
Kerberos credential cache (`kinit`). Otherwise prepends
`WINRM_DOMAIN` to the username when set.
Parameters
----------
args
Object with `WINRM_USERNAME`,
`WINRM_PASSWORD`, `WINRM_TRANSPORT`, and optionally
`WINRM_DOMAIN`.
Returns
-------
tuple
`(username, password)` suitable for
pypsrp or pywinrm.
"""
username = getattr(args, 'WINRM_USERNAME', None)
password = getattr(args, 'WINRM_PASSWORD', None)
transport = (getattr(args, 'WINRM_TRANSPORT', None) or '').lower()
if transport in ('kerberos', 'negotiate') and (not username or not password):
return (None, None)
if getattr(args, 'WINRM_DOMAIN', None):
return (f'{username}@{args.WINRM_DOMAIN}', password)
return (username, password)
def _map_transport(args):
"""
Derive PSRP auth method, SSL flag, and port from `args`.
Parameters
----------
args
Object with `WINRM_TRANSPORT`.
Returns
-------
tuple
`(psrp_auth, use_ssl, port)`.
"""
transport = (getattr(args, 'WINRM_TRANSPORT', None) or '').lower()
psrp_auth = _AUTH_MAP.get(transport, 'negotiate')
use_ssl = transport == 'ssl'
port = 5986 if use_ssl else 5985
return (psrp_auth, use_ssl, port)
def _pywinrm_transport(args, auth):
"""
Return the pywinrm transport for `args`, which knows no `negotiate`.
`negotiate`, the documented default, is what pypsrp speaks; pywinrm refuses it with
"unsupported auth method", and a missing transport the same way. Negotiate picks
Kerberos or NTLM, so without credentials, where `_build_auth()` leaves the Kerberos
credential cache to it, it becomes `kerberos`, and with credentials `ntlm`. Every
other value is one pywinrm knows and passes as it is. Verified against pywinrm
v0.5.0 (`winrm/transport.py`, `build_session()`).
Parameters
----------
args
Object with `WINRM_TRANSPORT`.
auth : tuple
`(username, password)` as `_build_auth()` returns it.
Returns
-------
str
The transport to hand to `winrm.Session()`.
"""
transport = (getattr(args, 'WINRM_TRANSPORT', None) or '').lower()
if transport in ('', 'negotiate'):
return 'ntlm' if auth[0] and auth[1] else 'kerberos'
return transport
def _ps_literal(value):
"""
Return a PowerShell expression that evaluates to `str(value)`, whatever it holds.
The value travels base64-encoded and is decoded on the remote host, so it never
appears in the script text. Quoting cannot give that guarantee: PowerShell closes a
single-quoted string on the typographic quotes U+2018 to U+201B as well, so a value
carrying one of them ends the literal and turns the rest into script, however the
ASCII quote is escaped. Verified against Windows PowerShell 5.1 on Windows Server
2025 and PowerShell 7.6 on RHEL 9. The base64 alphabet contains no quote and no
operator, which fixes the boundaries of the value before the value is known.
Parameters
----------
value
The value (converted to `str`).
Returns
-------
str
A parenthesized expression, usable as an argument or parameter value.
"""
encoded = txt.to_text(base64.b64encode(txt.to_bytes(str(value))))
return (
f"([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('{encoded}')))"
)
def _native_call(cmd, params):
"""
Return a command line that runs `cmd` with `params` without `cmd.exe` parsing them.
WinRS hands a command line to `cmd.exe`, where `&`, `|` and `>` in an argument start
a second command. The command line returned here holds nothing but base64: it starts
PowerShell with an encoded script that calls `cmd` with each argument decoded from
its own literal. A program that cannot be started yields return code 1 and the
reason on stderr, as it would from `cmd.exe`, instead of `exit $null` reporting
success.
Parameters
----------
cmd : str
The program to run.
params : list
Its arguments (each converted to `str`).
Returns
-------
str
The command line to hand to WinRS.
"""
call = ' '.join(['&', *(_ps_literal(item) for item in [cmd, *params])])
script = (
"$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue'; "
f'try {{ {call} }} '
'catch { [Console]::Error.WriteLine($_.ToString()); exit 1 }; '
'exit $LASTEXITCODE'
)
encoded = txt.to_text(base64.b64encode(txt.to_bytes(script, encoding='utf-16-le')))
return f'powershell.exe -NoProfile -NonInteractive -EncodedCommand {encoded}'
def _within(timeout, func, *args):
"""
Return what `func(*args)` returns, or a timeout result when it takes longer.
Neither backend bounds a whole call: both poll for output again and again while the
remote command runs, so a command that hangs blocks the caller forever. The call
runs in a daemon thread instead, which the caller leaves behind when the timeout
has passed; it ends with the process. The remote command keeps running until the
WinRM service closes the shell nobody polls any more: after `_IDLE_TIMEOUT` for the
runspace of `run_ps()` over pypsrp 0.9 and newer, after the idle timeout of the
service otherwise (two hours by default).
Parameters
----------
timeout : int or float or None
Seconds to wait. `None` waits as long as the call takes.
func : callable
The call, returning a result dictionary.
*args
Its arguments.
Returns
-------
dict
The result of `func`, or `{'retc': 1, 'stdout': '',
'stderr': 'Timeout after <timeout> seconds.'}`.
"""
if timeout is None:
return func(*args)
results = []
worker = threading.Thread(target=lambda: results.append(func(*args)))
worker.daemon = True
worker.start()
worker.join(timeout)
if results:
return results[0]
return {
'retc': 1,
'stdout': '',
'stderr': f'Timeout after {timeout} seconds.',
}
def _run_cmd(args, cmd, params):
"""Run `run_cmd()` without a timeout, see there."""
auth = _build_auth(args)
command = _native_call(cmd, params) if params else cmd
if HAVE_JEA:
try:
_psrp_auth, _use_ssl, _port = _map_transport(args)
session = Client(
server=args.WINRM_HOSTNAME,
username=auth[0],
password=auth[1],
auth=_psrp_auth,
ssl=_use_ssl,
port=_port,
cert_validation=True,
)
stdout, stderr, rc = session.execute_cmd(command)
return {
'retc': rc,
'stdout': txt.to_text(stdout, errors='strict_or_latin1'),
'stderr': txt.to_text(stderr, errors='strict_or_latin1'),
}
except Exception as e:
return {
'retc': 1,
'stdout': '',
'stderr': txt.exception2text(e),
}
if HAVE_WINRM:
try:
session = winrm.Session(
args.WINRM_HOSTNAME,
auth=auth,
transport=_pywinrm_transport(args, auth),
)
result = session.run_cmd(command)
return {
'retc': result.status_code,
'stdout': txt.to_text(result.std_out, errors='strict_or_latin1'),
'stderr': txt.to_text(result.std_err, errors='strict_or_latin1'),
}
except Exception as e:
return {
'retc': 1,
'stdout': '',
'stderr': txt.exception2text(e),
}
return {
'retc': 1,
'stdout': '',
'stderr': 'No compatible remoting library available (pypsrp or pywinrm).',
}
def run_cmd(args, cmd, params=None, timeout=None):
"""
Run a native command on a remote Windows host via WinRM/PSRP and return a
normalized result dictionary.
Prefers **pypsrp (PSRP)** if available (for JEA/PowerShell Remoting
compatibility); otherwise falls back to **pywinrm**. Authentication,
transport and SSL/port selection are derived from the provided `args`.
Parameters
----------
args
An object (e.g., `argparse.Namespace`) that provides at least:
- `WINRM_HOSTNAME` (`str`): Target host or IP.
- `WINRM_USERNAME` (`str`, optional): Username. If `None` or empty when using
Kerberos transport, will use existing Kerberos credentials from credential cache
(e.g., obtained via `kinit`).
- `WINRM_PASSWORD` (`str`, optional): Password. If `None` or empty when using
Kerberos transport, will use existing Kerberos credentials from credential cache.
- `WINRM_TRANSPORT` (`str`, optional): Transport (e.g., `'negotiate'`, `'kerberos'`,
`'ntlm'`, `'credssp'`, `'basic'`, `'ssl'`). Defaults to `'negotiate'` if unset.
- `WINRM_DOMAIN` (`str`, optional): If set, username is sent as `user@domain`.
(Additional fields may be honored by the underlying libraries if present.)
cmd : str
The executable/command to run remotely (native command, not a PowerShell
script block). Without `params` it is handed to `cmd.exe` as it stands, so it
must not contain untrusted data.
params : list[str], optional
Positional arguments passed to the command. Each
one reaches the program as a single argument, whatever it contains: `cmd.exe`
never parses them. Defaults to `None`, which sends no arguments.
timeout : int or float, optional
Seconds to wait for the result. After that the call returns a result with
`retc` 1 and `Timeout after <timeout> seconds.` in `stderr`. Defaults to
`None` (no timeout).
Returns
-------
dict
A normalized result with:
- `retc` (`int`): Process return code (`0` on success).
- `stdout` (`str`): Captured standard output (text).
- `stderr` (`str`): Captured standard error (text).
Notes
-----
- If **pypsrp** is available, maps `WINRM_TRANSPORT` to an appropriate PSRP auth
and chooses SSL/port (5986 for SSL, 5985 otherwise), then executes the command
via `Client.execute_cmd()`.
- If pypsrp is unavailable but **pywinrm** is installed, executes via
`Session.run_cmd()`.
- With `params`, the command runs through an encoded PowerShell call rather than
through `cmd.exe`, which would read `&`, `|` or `>` in an argument as the start
of another command. Return code, stdout and stderr are those of the program. A
`.bat` or `.cmd` file is still interpreted by `cmd.exe`, arguments included.
- For Kerberos authentication: if `WINRM_USERNAME` and `WINRM_PASSWORD` are not provided
(or are empty/None), the function will attempt to use existing Kerberos credentials
from the credential cache (obtained via `kinit`).
- On any exception, returns `{'retc': 1, 'stdout': '', 'stderr': <exception text>}`.
- If neither backend is present, returns an error indicating that no compatible
remoting library is available.
Examples
--------
>>> # With explicit credentials:
>>> run_cmd(args, 'ipconfig', ['/all'])
{'retc': 0, 'stdout': 'Windows IP Configuration\\r\\n...','stderr': ''}
>>> # With Kerberos using kinit credentials (username/password can be None):
>>> run_cmd(args, 'ipconfig', ['/all'])
{'retc': 0, 'stdout': 'Windows IP Configuration\\r\\n...','stderr': ''}
"""
return _within(timeout, _run_cmd, args, cmd, params)
def _psrp_objects_to_text(output):
"""
Render the output objects of a PSRP pipeline as text, like `Format-List`.
Behind a JEA endpoint the pipeline cannot end in `Out-String`, which the endpoint
may not expose, so the objects arrive deserialized, and `str()` of one is only
what its `ToString()` returns: the name of a service, the type name of most
others. Each property of a complex object becomes a line `Name : Value`, objects
are separated by an empty line; a plain value (a string, a number) stays as it is.
Parameters
----------
output : list
What `PowerShell.invoke()` returned.
Returns
-------
str
The text.
"""
blocks = []
for obj in output:
properties = {}
properties.update(getattr(obj, 'adapted_properties', None) or {})
properties.update(getattr(obj, 'extended_properties', None) or {})
if not properties:
blocks.append(str(obj))
continue
width = max(len(str(name)) for name in properties)
blocks.append(
'\n'.join(
f'{str(name).ljust(width)} : {"" if value is None else value}'
for name, value in properties.items()
)
)
separator = '\n\n' if any('\n' in block for block in blocks) else '\n'
return separator.join(blocks)
# What PowerShell accepts as a parameter name. A name is spliced into the script text as
# it stands, so anything else could carry script of its own.
_PS_PARAMETER_NAME = re.compile(r'[A-Za-z_][A-Za-z0-9_]*')
# Seconds after which the WinRM service closes a runspace whose client stopped polling,
# such as one left behind by a timeout. A client that waits for output polls at least
# every 20 seconds, so a command that runs longer is not affected. The service default
# of two hours lets abandoned runspaces pile up until the shell quota of the account
# (30 by default) refuses every further connection. Verified against Windows Server
# 2025: such a runspace was gone about two minutes later instead of two hours.
_IDLE_TIMEOUT = 60
def _runspace_pool(runspace_pool_class, wsman, configuration_name):
"""
Create the pypsrp runspace pool, with `_IDLE_TIMEOUT` where pypsrp supports it.
`idle_timeout` exists from pypsrp 0.9.0 on, which needs Python 3.10. On Python 3.9,
as on RHEL 8 and 9, the newest pypsrp is 0.8.1, whose pool takes no such argument and
keeps the idle timeout of the service. Verified against pypsrp 0.8.1 and 0.9.1.
Parameters
----------
runspace_pool_class : type
`pypsrp.powershell.RunspacePool`.
wsman : pypsrp.wsman.WSMan
The connection the pool runs on.
configuration_name : str
The session configuration (endpoint) to connect to.
Returns
-------
pypsrp.powershell.RunspacePool
The pool, not opened yet.
"""
try:
return runspace_pool_class(
wsman,
configuration_name=configuration_name,
idle_timeout=_IDLE_TIMEOUT,
)
except TypeError:
# pypsrp 0.8.1 and older: unexpected keyword argument 'idle_timeout'
return runspace_pool_class(wsman, configuration_name=configuration_name)
def _run_ps(args, cmd, params):
"""Run `run_ps()` without a timeout, see there."""
auth = _build_auth(args)
configuration_name = getattr(
args,
'WINRM_CONFIGURATION_NAME',
None,
)
if configuration_name and not HAVE_JEA:
return {
'retc': 1,
'stdout': '',
'stderr': 'WINRM_CONFIGURATION_NAME requires '
'pypsrp (JEA). Install pypsrp or '
'unset '
'--winrm-configuration-name.',
}
if HAVE_JEA:
try:
from pypsrp.powershell import (
PowerShell,
RunspacePool,
)
from pypsrp.wsman import WSMan
_psrp_auth, _use_ssl, _port = _map_transport(args)
wsman = WSMan(
server=args.WINRM_HOSTNAME,
username=auth[0],
password=auth[1],
auth=_psrp_auth,
ssl=_use_ssl,
port=_port,
cert_validation=True,
)
with _runspace_pool(
RunspacePool,
wsman,
configuration_name or 'Microsoft.PowerShell',
) as pool:
ps = PowerShell(pool)
if params is not None:
ps.add_cmdlet(cmd)
if isinstance(params, dict):
for name, value in params.items():
ps.add_parameter(name, value)
else:
for param in params:
ps.add_argument(param)
else:
ps.add_script(cmd)
if not configuration_name:
# Over PSRP the output arrives as objects, and `str()` of an object is
# its type name ("System.ServiceProcess.ServiceController"), not what
# PowerShell shows for it. Render it as text on the remote side, the
# way pywinrm and a local run deliver it. A JEA endpoint may not
# expose Out-String, so there the objects stay as they are.
ps.add_cmdlet('Out-String').add_parameter('Stream', True)
output = ps.invoke()
if configuration_name:
# Without Out-String the objects arrive deserialized; show their
# properties the way Format-List does, so the text says what they hold.
stdout = _psrp_objects_to_text(output)
else:
stdout = '\n'.join(str(o) for o in output)
stderr_lines = []
for err in ps.streams.error:
try:
stderr_lines.append(
err.to_string(),
)
except Exception:
msg = getattr(err, 'message', None) or str(err)
stderr_lines.append(str(msg))
stderr = '\n'.join(stderr_lines)
return {
'retc': 0 if not ps.had_errors else 1,
'stdout': txt.to_text(stdout, errors='strict_or_latin1'),
'stderr': txt.to_text(stderr, errors='strict_or_latin1'),
}
except Exception as e:
return {
'retc': 1,
'stdout': '',
'stderr': txt.exception2text(e),
}
if HAVE_WINRM:
try:
session = winrm.Session(
args.WINRM_HOSTNAME,
auth=auth,
transport=_pywinrm_transport(args, auth),
)
# pywinrm only runs script text, so the structured call pypsrp makes is
# rebuilt here: the command and every value are decoded from literals of
# their own, and a parameter name has to be one before it is spliced in.
if params is not None:
if isinstance(params, dict):
for name in params:
# fullmatch: `$` would let a trailing newline through
if not _PS_PARAMETER_NAME.fullmatch(str(name)):
return {
'retc': 1,
'stdout': '',
'stderr': f'Invalid PowerShell parameter name: {name}',
}
arguments = [
f'-{name} {_ps_literal(value)}'
for name, value in params.items()
]
else:
arguments = [_ps_literal(param) for param in params]
ps_cmd = ' '.join(['&', _ps_literal(cmd), *arguments])
else:
ps_cmd = cmd
# pywinrm turns the CLIXML progress stream of PowerShell into text and says
# so with a Python warning on stderr when that stream is not well-formed,
# which the German progress messages of Windows Server 2025 are not. That
# warning would end up in the output; the stream itself is dropped
# below on success anyway.
with warnings.catch_warnings():
warnings.simplefilter('ignore')
result = session.run_ps(ps_cmd)
result = {
'retc': result.status_code,
'stdout': txt.to_text(result.std_out, errors='strict_or_latin1'),
'stderr': txt.to_text(result.std_err, errors='strict_or_latin1'),
}
if result['retc'] == 0 and result['stderr'].startswith(
'#< CLIXML',
):
result['stderr'] = ''
return result
except Exception as e:
return {
'retc': 1,
'stdout': '',
'stderr': txt.exception2text(e),
}
return {
'retc': 1,
'stdout': '',
'stderr': 'No compatible remoting library available (pypsrp or pywinrm).',
}
def run_ps(args, cmd, params=None, timeout=None):
"""
Run PowerShell on a remote Windows host via WinRM/PSRP
and return a normalized result dictionary.
Prefers **pypsrp (PSRP)** if available (best for
JEA/PowerShell Remoting); otherwise falls back to
**pywinrm**.
Parameters
----------
args
Object (e.g. `argparse.Namespace`) with:
- `WINRM_HOSTNAME` (`str`): Target host or IP.
- `WINRM_USERNAME` (`str`, optional): Username.
If empty with Kerberos transport, the credential
cache (`kinit`) is used.
- `WINRM_PASSWORD` (`str`, optional): Password.
Same Kerberos fallback as username.
- `WINRM_TRANSPORT` (`str`, optional): Transport
(e.g. `'negotiate'`, `'kerberos'`, `'ntlm'`,
`'credssp'`, `'basic'`, `'ssl'`).
Defaults to `'negotiate'`.
- `WINRM_DOMAIN` (`str`, optional): If set,
username is sent as `user@domain`.
- `WINRM_CONFIGURATION_NAME` (`str`, optional):
JEA endpoint name. Defaults to
`'Microsoft.PowerShell'`. Only with **pypsrp**.
cmd : str
What to execute remotely. Meaning
depends on `params`:
- `params is None`: `cmd` is an arbitrary
PowerShell script (pipelines, expressions, etc.)
executed via `add_script()`.
- `params` given (`list` or `dict`): `cmd` is a
single cmdlet name executed via `add_cmdlet()`
(optimal for JEA allow/deny).
params : list[str], dict, or None
- `None` (default): no params, `cmd` is run as a
script.
- `list[str]`: positional arguments added via
`add_argument()`.
- `dict`: named parameters added via
`add_parameter(name, value)`.
Values may be untrusted: each one reaches the cmdlet
as a single value, whatever it contains. With
**pywinrm** every value is converted to `str`, and a
parameter name that PowerShell would not accept is
refused with `retc` 1.
timeout : int or float, optional
Seconds to wait for the result. After that the call returns a result with
`retc` 1 and `Timeout after <timeout> seconds.` in `stderr`. Defaults to
`None` (no timeout).
Returns
-------
dict
Normalized result with:
- `retc` (`int`): `0` if no errors.
- `stdout` (`str`): Captured output.
- `stderr` (`str`): Error/diagnostic output.
For **pywinrm**: CLIXML progress noise is
suppressed when `retc == 0`.
Examples
--------
Pipeline (params=None, uses add_script):
>>> run_ps(args, 'Get-Process | Select -First 1')
Positional params (uses add_cmdlet + add_argument):
>>> run_ps(args, 'Get-Service', ['WinRM'])
Named params (uses add_cmdlet + add_parameter):
>>> run_ps(
... args,
... 'Get-WmiObject',
... {'Class': 'Win32_OperatingSystem'},
... )
"""
return _within(timeout, _run_ps, args, cmd, params)