【问题标题】:PowerShell array issue_PowerShell 数组问题_
【发布时间】:2022-01-13 21:17:21
【问题描述】:

我一直在写一个powershell脚本来解决一个问题,脚本的实用性可能会让一些人感到困惑,但我有一个用途。

脚本的目的是在临时文件夹中创建一个新目录,该目录与父文件夹中的文件夹名称相同,但由于脚本是临时文件夹中新创建的文件夹名称,其周围有以下文本他们@{Name=FOLDERNAME} 我怎样才能编辑脚本来获取 FOLDERNAME?

$dirs = @(Get-ChildItem -Path C:\Users\LTGoldman\Desktop\keys -Recurse -Directory -Force -ErrorAction SilentlyContinue | Select-Object Name)
for($i=0; $i -lt $dirs.length;$i++)
    {
        New-Item -Path "C:\Users\LTGoldman\Desktop\keys\temp" -Name $dirs[$i] -ItemType "directory"
        Move-Item -Path .\*.tar.gz -Destination C:\Users\LTGoldman\Desktop\keys\temp\$dirs[$i]
    }

改为:

$dirs = @(Get-ChildItem -Path C:\Users\LTGoldman\Desktop\keys -Recurse -Directory -Force -ErrorAction SilentlyContinue | Select-Object Name)
for($i=0; $i -lt $dirs.length;$i++)
    {
        New-Item -Path "C:\Users\LTGoldman\Desktop\newkeys" -Name $dirs[$i].Name -ItemType "directory"
        Move-Item -Path "C:\Users\LTGoldman\Desktop\keys\"+$dirs[$i]+"\*.tar.gz" -Destination C:\Users\LTGoldman\Desktop\newkeys\$dirs[$i].Name
    }

我不确定如何正确连接 Move-Item 行?

【问题讨论】:

  • 乍一看,这样做会解决你的问题$dirs[$i].Name(在两条线上)或者只是这样做Select-Object -ExpandProperty Name
  • 你还需要更正这个Move-Item -Path .\*.tar.gz,这些是哪些文件?每个 $dirs[$i] 中的那些?
  • 太棒了,这似乎成功了,文件夹目前是空的,但我会先调查一下。如果我有进一步的困难,我会回帖。

标签: arrays powershell


【解决方案1】:

通常你会使用foreach 循环来处理这个问题,它看起来也更干净:

$sourceFolder = 'C:\Users\LTGoldman\Desktop\keys'
$destinationFolder = 'C:\Users\LTGoldman\Desktop\keys\temp'

foreach($folder in Get-ChildItem $sourceFolder -Directory -Recurse)
{
    New-Item -Path $destinationFolder -Name $folder.Name -ItemType Directory
}

由于您使用的是-Recurse,您可能还需要处理文件夹冲突:

$newFolder = Join-Path $destinationFolder -ChildPath $folder.Name
if(Test-Path $newFolder)
{
    Write-Warning "$($folder.Name) already exists in $destinationFolder. Skipping."
    continue
}

另一种处理冲突的方法是使用try catch,假设没有冲突,如果有,跳过它:

try
{
    New-Item -Path $destinationFolder -Name $folder.Name -ItemType Directory
}
catch
{
    Write-Warning "$($folder.Name) already exists in $destinationFolder. Skipping."
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    • 2017-12-05
    • 1970-01-01
    相关资源
    最近更新 更多