如何在管道上的 cmdlet 之间传递常见的 powershell 命令行参数?
假设我有两个 cmdlet,“new-foo”和“do-bar”。这两个 cmdlet 都需要对服务进行身份验证才能执行其操作,并且“do-bar”采用 foo.今天,我可以做:
new-foo -host localhost -username user -password password -whateverOtherArgs
我可以做:
do-bar -host localhost -username user -password password -foo myFoo
我什至可以将它们链接到管道上传递 foo,例如:
new-foo <blah blah> | do-bar -host localhost -username user -password password
但我不知道如何传递公共参数,例如服务位置和元素之间的凭据管道。如果我将一堆 cmdlet 链接在一起,我只想在第一次传递凭据,然后将这些凭据重新用于管道的其余部分。
我错过了什么,看来这应该是显而易见的......
Say I've got two cmdlets, 'new-foo' and 'do-bar'. Both cmdlets need to authenticate to a service in order to perform their action, and 'do-bar' takes a foo. Today, I can do:
new-foo -host localhost -username user -password password -whateverOtherArgs
And I can do:
do-bar -host localhost -username user -password password -foo myFoo
And I can even chain them passing foo on the pipeline, e.g.:
new-foo <blah blah> | do-bar -host localhost -username user -password password
But I can't figure out how to pass the common parameters, such as the service location and the credentials between elements of the pipeline. If I've got a bunch of my cmdlets chained together I'd like to only pass the credentials the first time, and then re-use those for the rest of the pipeline.
What am I missing, seems like this should be obvious ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以让 New-Foo 吐出一个对象,其中包含 do-bar 感兴趣的原始对象以及服务位置和凭证作为属性。如果用户不提供 ServiceLocation 或 Credential 参数,则接受此对象作为参数,然后提取所需的数据。
You could have New-Foo spit out an object that contains both the original object that do-bar is interested in as well as the service location and the credentials as properties. Accept this object as a parameter and then pluck out the data you need if the user doesn't supply the ServiceLocation or Credential parameters.
Get-Credential 是否满足您的需求。
does Get-Credential cover you need.
您是在开发此 cmdlet,还是只是在脚本中使用它们?
如果您使用任何 OOP 语言编写这些 cmdlet,我认为一种方法是您有一个基本 cmdlet 类,并且所有其他 cmdlet 都应该扩展该基本 cmdlet 类。在这种情况下,基本 cmdlet 类应初始化一个存储您的凭据的对象,并有一个 cmdlet 来请求凭据,从而初始化该对象。因此,扩展基类的所有其他 cmdlet 都可以在此对象中查找凭据。
Are you developing this cmdlets, or are you just using them in your scripts?
If you are writing these cmdlets in any OOP language, I think a way to do it is that you have a base cmdlet class, and every other cmdlets should extend that base cmdlet class. In this case, the base cmdlet class should initialize an object that stores your credential, and have a cmdlet to ask for credentials, which initialize the object. Every other cmdlets that extends the base class can therefore look for credential in this object.