简体   繁体   English

PowerShell 阵列问题_

[英]PowerShell array issue_

I have been writing a powershell script to solve a problem, the utility of the script may baffle some but I have a use in mind.我一直在写一个 powershell 脚本来解决一个问题,该脚本的实用性可能会让一些人感到困惑,但我有一个用途。

The aim of the script is to create a new directory in the temp folder that mirrors the name of the folder in the parent folder but with the script as it is the newly created folder names in the temp folder have the following text around them @{Name=FOLDERNAME} how can I edit the script just to get FOLDERNAME?该脚本的目的是在临时文件夹中创建一个新目录,该目录反映父文件夹中文件夹的名称,但使用脚本,因为它是临时文件夹中新创建的文件夹名称,它们周围有以下文本@{ 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]
    }

Changed to:变成:

$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
    }

I am not sure how to concatenate the Move-Item line properly?我不确定如何正确连接 Move-Item 行?

Normally you would use a foreach loop to handle this, it also looks cleaner:通常你会使用一个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
}

Since you're using -Recurse you might also will need to handle collision of folders:由于您使用的是-Recurse ,您可能还需要处理文件夹的冲突:

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

Another way to handle collision would be with a try catch , just assume there is no collision and if there is, skip it:另一种处理碰撞的方法是使用try catch ,假设没有碰撞,如果有,跳过它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM