PowerShell 中的触摸功能

2024-05-09

我最近在 PowerShell 配置文件中添加了触摸功能

PS> notepad $profile
function touch {Set-Content -Path ($args[0]) -Value ($null)}

保存并运行测试

touch myfile.txt

返回错误:



touch : The term 'touch' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At line:1 char:1
+ touch myfile
+ ~~~~~
    + CategoryInfo          : ObjectNotFound: (touch:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
  

对于 PowerShell,函数有命名约定。强烈建议坚持这一点,如果您将这些函数放入模块中并导入它,就不会再收到有关它的警告。

可以找到有关命名约定的好读物here https://blogs.technet.microsoft.com/heyscriptingguy/2011/07/01/naming-and-designing-advanced-powershell-functions/.

话虽如此,Powershell 确实为您提供了以下功能:Aliasing这就是您在下面的函数中可以看到的内容。

正如 Jeroen Mostert 和其他人已经解释的那样,Touch 函数并不是要销毁内容,而只是将 LastWriteTine 属性设置为当前日期。 此函数允许您在参数中自己指定日期NewDate,但如果您省略它,它将默认为当前日期和时间。

function Set-FileDate {
    [CmdletBinding()]
    param(
        [Parameter(ValueFromPipeline = $true, Mandatory = $true, Position = 0)]
        [string[]]$Path,
        [Parameter(Mandatory = $false, Position = 1)]
        [datetime]$NewDate = (Get-Date),
        [switch]$Force
    )
    Get-Item $Path -Force:$Force | ForEach-Object { $_.LastWriteTime = $NewDate }
}
Set-Alias Touch Set-FileDate -Description "Updates the LastWriteTime for the file(s)"

现在,该函数有一个 PowerShell 不会反对的名称,但通过使用Set-Alias您可以通过调用它在代码中引用它touch

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

PowerShell 中的触摸功能 的相关文章

随机推荐