Powershell - 脚本在函数外部工作但不在函数内工作

2023-12-31

我正在尝试编写一个简单的函数,该函数从指定目录获取文件,使用一个条件过滤它们,然后将结果放回。我想出了如下。如果它没有放置在函数中,则它可以工作,而当放置在函数中时,它只运行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
    }
}

虽然我无法解释您的症状,但您可以bypass通过简化代码并避免Set-Location调用(最好避免,因为它们会改变当前位置会话范围内):

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

Note: The -WhatIf common parameter https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_commonparameters#whatif in the command above previews the operation. Remove -WhatIf once you're sure the operation will do what you want.

以上删除了所有.pdf文件夹中的文件$Path没有子串sig以他们的名义 - 这就是我理解你的意图。


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

function Remove-AllUnsigned {

  [CmdletBinding(SupportsShouldProcess, ConfirmImpact='None')]
  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*

}

Note:

  • 由于该函数的设计目的不是接受管道输入,不需要process阻止(尽管这不会造成伤害)。

  • Since 即时删除可能很危险,$PSCmdlet.ShouldContinue()默认用于提示用户确认 - 除非你明确通过-Force

    • 显示的提示是$PSCmdlet.ShouldContinue() https://learn.microsoft.com/en-US/dotnet/api/System.Management.Automation.PSCmdlet.ShouldContinue默认为 YES,因为响应很不幸;GitHub 问题 #9428 https://github.com/PowerShell/PowerShell/issues/9428建议引入一个新的重载,允许默认为 NO。
  • 为了使函数本身也支持-WhatIf通用参数 https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_commonparameters#whatif for 预览经营、财产SupportsShouldProcess in the [CmdletBinding()]属性被设置(隐式为$true),但是ConfirmImpact属性设置为None, 鉴于.ShouldContinue()将无条件地处理提示(请注意,明确使用-Confirm仍会造成ShouldProcess-相关提示)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Powershell - 脚本在函数外部工作但不在函数内工作 的相关文章

随机推荐