Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
要添加到表达式末尾的Powershell开关参数_Powershell - Fatal编程技术网

要添加到表达式末尾的Powershell开关参数

要添加到表达式末尾的Powershell开关参数,powershell,Powershell,以下是我想做的: param([Switch]$myparameter) If($myparamter -eq $true) {$export = Export-CSV c:\temp\temp.csv} Get-MyFunction | $export 如果传递了$myparameter,则将数据导出到所述位置。否则,只显示正常输出(换句话说,忽略$export)。这里不起作用的是将$export设置为“导出csv…”。用引号括起来是行不通的 我试图避免使用if,then语句,该语句说“如果

以下是我想做的:

param([Switch]$myparameter)
If($myparamter -eq $true) {$export = Export-CSV c:\temp\temp.csv}
Get-MyFunction | $export
如果传递了$myparameter,则将数据导出到所述位置。否则,只显示正常输出(换句话说,忽略$export)。这里不起作用的是将$export设置为“导出csv…”。用引号括起来是行不通的

我试图避免使用if,then语句,该语句说“如果它已通过,请导出它。如果它未通过,请输出数据”

我有一个更大的模块,所有的东西都在里面工作,所以我希望这样做是有原因的。如果需要其他信息,请告诉我

提前谢谢大家

我试图避免一个if,then语句

呃,如果你坚持

param([Switch]$myparameter)

$cmdlet, $params = (('Write-output', @{}), 
                    ('Export-Csv', @{'LiteralPath'='c:\temp\temp.csv'}))[$myparameter]

Get-MyFunction | & $cmdlet @params

tl;医生:

param([Switch] $myparameter)

# Define the core command as a *script block* (enclosed in { ... }),
# to be invoked later, either with operator . (no child variable scope) 
# or & (with child variable scope)
$scriptBlock = { Get-MyFunction }

# Invoke the script block with . (or &), and pipe it to the Export-Csv cmdlet,
# if requested.
If ($myparameter) { # short for: ($myparameter -eq $True), because $myparameter is a switch
  . $scriptBlock | Export-Csv c:\temp\temp.csv
} else {
  . $scriptBlock
}

简洁、有效,并巧妙地使用了许多高级功能-但是,尽管它避免了要求的
if
语句,但在这种情况下,这样做可能不会产生最佳或最可读的解决方案

您要寻找的是将命令存储在变量中以供以后执行,但您自己的尝试是:

If ($myparameter -eq $true) { $export = Export-CSV c:\temp\temp.csv }
导致立即执行,这不仅是意外的,而且是失败的,因为
Export Csv
cmdlet在上述语句中缺少输入

您可以通过脚本块将源代码片段存储在变量中供以后执行,只需将该片段封装在
{…}
中即可,在您的示例中,这意味着:
If($myparameter-eq$true){$export={export Csv c:\temp\temp.Csv}}

请注意,如果传递给
的本身就是一个脚本块,但根据定义,只要发现
如果
条件为真,就会立即执行该脚本块

然后,可以使用以下两个运算符之一根据需要调用包含脚本块的变量:

  • ,“点源”操作符,在当前范围内执行脚本块
  • &
    ,调用运算符,在子作用域中执行与潜在变量定义相关的脚本块
但是,如果指定了switch
$myparameter
,那么您只需要使用带有附加命令的管道,那么最好更改逻辑:

  • 将共享核心命令
    Get MyFunction
    存储在脚本块的变量
    $scriptBlock

  • if
    语句中调用该脚本块,可以是独立的(默认情况下),也可以通过管道将其传输到
    导出Csv
    (如果指定了
    -MyParameter


不幸的是,我无法让它工作。有没有一篇文章可以让我了解更多语法知识?我以前从未见过这种情况。请注意,我使用的是PowerShell 5.0。另外,非常感谢。@MattRemis哪种语法<代码>&
是,它从字符串运行命令
$x,$y=@(1,2)
是变量赋值,但似乎并不知道它可以解包集合
($a,$b)[]
是数组索引,依赖于隐式转换为[int]的参数0/1<代码>$var=@{};cmd@var是。@MattRemis我也从来没有见过它像这样组合在一起,是我编造的。虽然它在技术上避免了
if
,但它并不真正推荐它。但是如果,为什么要避免使用
@mklement0的答案更明智、更直截了当。。。