我正在构建一个用于出色打印的 Powershell CmdLet。它的功能应该与winprintOut-Print
的所有花里胡哨的功能一样。
PS> get-help out-winprint
NAME
Out-WinPrint
SYNTAX
Out-WinPrint [[-Name] <string>] [-SheetDefintion <string>] [-ContentTypeEngine <string>]
[-InputObject <psobject>] [<CommonParameters>]
ALIASES
wp
为此,我需要获取InputObject
我的实现的输入流 ( )PSCmdLet
并将其传递,Out-String
因此它全部被扩展和格式化。我在想最好的方法是使用CommandInvocationIntrinsics.InvokeScript
to invoke out-string
,它应该给我一个字符串的输出......
protected override void ProcessRecord() {
if (InputObject == null || InputObject == AutomationNull.Value) {
return;
}
IDictionary dictionary = InputObject.BaseObject as IDictionary;
if (dictionary != null) {
// Dictionaries should be enumerated through because the pipeline does not enumerate through them.
foreach (DictionaryEntry entry in dictionary) {
ProcessObject(PSObject.AsPSObject(entry));
}
}
else {
ProcessObject(InputObject);
}
}
private void ProcessObject(PSObject input) {
object baseObject = input.BaseObject;
// Throw a terminating error for types that are not supported.
if (baseObject is ScriptBlock ||
baseObject is SwitchParameter ||
baseObject is PSReference ||
baseObject is PSObject) {
ErrorRecord error = new ErrorRecord(
new FormatException("Invalid data type for Out-WinPrint"),
DataNotQualifiedForWinprint,
ErrorCategory.InvalidType,
null);
this.ThrowTerminatingError(error);
}
_psObjects.Add(input);
}
protected override async void EndProcessing() {
base.EndProcessing();
//Return if no objects
if (_psObjects.Count == 0) {
return;
}
var text = this.SessionState.InvokeCommand.InvokeScript(@"Out-String", true, PipelineResultTypes.None, _psObjects, null);
// Just for testing...
this.WriteObject(text, false);
...
假设我像这样调用了我的 cmdlet:
PS> get-help out-winprint -full | out-winprint`
如果我理解这应该如何工作,那么text
上面的 var 应该是 astring
并且WriteObject
call 应该显示out-string
将显示的内容(即 的结果get-help out-winprint -full
)。
然而,实际上text
是string[] = { "" }
(具有一个元素的字符串数组,一个空字符串)。
我究竟做错了什么?