如何将vars传递到PowerShell中的嵌套循环中?

时间:2018-09-02 12:40:09

标签: powershell input

我正在尝试编写一个小的PowerShell脚本来清​​理某些日志转储中的文件名,但是我似乎被卡住了……我从各种来源转储了日志,文件名似乎变得乱七八糟。

我正在寻找类似这样的文件名...“ Source-Service.log”

Get-ChildItem *.* -Path ~/Desktop/New | ForEach-Object {
    while ([string]($_.Name) -notmatch "^[a-z].*" -or [string]($_.Name) -notmatch "^[A-Z].*") {
        Rename-Item -NewName { [string]($_.Name).Substring(1) }
    }
    Write-Host $_.Name
}

输出似乎出错了。

Rename-Item : Cannot evaluate parameter 'NewName' because its argument is
specified as a script block and there is no input. A script block cannot be
evaluated without input.
At line:8 char:30
+         Rename-Item -NewName { $File.Substring(1) }
+                              ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (:) [Rename-Item], ParameterBindingException
    + FullyQualifiedErrorId : ScriptBlockArgumentNoInput,Microsoft.PowerShell.Commands.RenameItemCommand

想法是检查文件名以查看它是否是字符,如果不删除它,则删除“。-/和空格”

我所针对的原始文件是这样的:

1. source - data (1).log
100. - source - Data.log
(1)  Source - data.log
source - data.log
<space><space> source - data.log

从上面寻找的结果是:我不担心重复的文件名,因为源和数据每天都在变化,并且文件夹会定期清除...

source - data (1).log
source - Data.log
Source - data.log
source - data.log
source - data.log

有人可以告诉我如何克服这个错误吗?

2 个答案:

答案 0 :(得分:0)

如果您的目标是删除前导非字母字符,则可以简化操作:

$files = Get-ChildItem -Path ~\Desktop\New -File

foreach ($file in $files)
{
    if ($file.BaseName -notmatch '\S+\s-')
    {
        $newName = $file.Name -replace '^.+?(?=[a-z])'
        $newName = Join-Path $file.DirectoryName $newName

        if (Test-Path -Path $newName)
        {
            Remove-Item -Path $newName
        }
        $file | Rename-Item -NewName $newName

        Write-Verbose $newName
    }
}

这将迭代您的列表并查找您的模式,并在必要时重命名。假设:source没有空格。

答案 1 :(得分:-1)

  1. 这可能会有所帮助:Remove-NonAlphanumericCharFromString
  2. 了解如何删除非字母数字,请使用文件的基本名称(不带路径和扩展名的名称)。
  3. 用空字符串替换不需要的字符。

    $pattern = '[^a-zA-Z]'
    Set-Location <YourDir>
    Get-Childitem | Foreach-Object {
        Rename-Item -Path ".\$($_.Name)" -NewName "$($_.BaseName -replace $pattern,'')$($_.extension)"
    }
    
  4. 请注意,如果需要覆盖现有文件,上述操作将失败。