【问题标题】:Powershell - Script working outside function but not in functionPowershell - 脚本在函数外工作但不在函数内
【发布时间】:2022-01-26 14:36:03
【问题描述】:

我正在尝试编写一个简单的函数,该函数从指定目录中获取文件,使用一个标准过滤它们,然后将结果放回去。我想出这个如下。如果它没有放在一个函数中,它就可以工作,而当它放在一个函数中时,它只运行Get-ChildItem,我不知道为什么。 这是我的简单代码:

function Move-AllSigned 
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true)]
        [string] $Path
    )
               
    Process {
        $TempPath = Join-Path -Path $Path -ChildPath '\1'

        Write-Host $TempPath

        Set-Location -Path $Path
        Get-ChildItem -Name "*sig*" | Move-Item -Destination $TempPath
        Remove-Item *.pdf 
        Set-Location -Path $TempPath
        Move-Item * -Destination $Path
    }
}

【问题讨论】:

  • 为什么在Get-ChildItem 上使用-Name 参数?
  • 我建议使用PushPop 位置而不是Set-Location 甚至更好,忘记更改目录并使用绝对路径工作。
  • 用于仅选择包含名称部分 sig 的文件。
  • @BalifOne, -Name 与 cmdlet 的 匹配 行为无关。它只要求输出路径strings(相对于输入路径)而不是objects

标签: powershell


【解决方案1】:

虽然我对您的症状没有任何解释,但您可以通过简化代码并避免 Set-Location 调用来绕过它(最好避免,因为它们会更改当前位置 session-宽):

Remove-Item (Join-Path $Path *.pdf) -Exclude *sig* -WhatIf

注意:上面命令中的-WhatIf common parameter预览操作。一旦您确定该操作将执行您想要的操作,请删除 -WhatIf

以上内容删除了文件夹 $Path 中名称中没有子字符串 sig 的所有 .pdf 文件 - 我理解您的意图。


封装在一个函数中(省略错误处理):

function Remove-AllUnsigned {

  [CmdletBinding(SupportsShouldProcess)]
  param (
      [Parameter(Mandatory)]
      [string] $Path,
      [switch] $Force
  )

  # Ask for confirmation, unless -Force was passed.
  # Caveat: The default prompt response is YES, unfortunately.
  if (-not $Force -and -not $PSCmdlet.ShouldContinue($Path, "Remove all unsigned PDF files from the following path?")) { return }
  
  # Thanks to SupportsShouldProcess, passing -WhatIf to the function
  # is in effect propagated to cmdlets called inside the function.
  Remove-Item (Join-Path $Path *.pdf) -Exclude *sig*

}

注意:

  • 由于该函数不是为接受管道输入而设计的,因此不需要process 块(尽管它不会造成伤害)。

  • 由于即时删除可能很危险,默认使用$PSCmdlet.ShouldContinue()来提示用户确认 - 除非你明确传递-Force

  • 为使函数本身也支持-WhatIf common parameter进行预览操作,设置[CmdletBinding()]属性中的属性SupportsShouldProcess(隐式为$true

【讨论】:

  • 谢谢!这是一个好主意,它就像一个魅力。但是现在在函数内部工作的问题仍然存在。 A 甚至删除了 cmdlet biding 参数也无济于事。
  • @BalifOne,请查看我的更新。如果新添加的功能对您不起作用,则问题可能出在其他地方。
  • 非常感谢这次它可以正常工作并且完全按照它应该做的!我也很欣赏额外的线索和解释。干得好,对我有很大帮助!
  • 我很高兴听到这个消息,@BalifOne;我的荣幸。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-17
相关资源
最近更新 更多