AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / computer / 问题 / 1748231
Accepted
Cheloveshka
Cheloveshka
Asked: 2022-10-19 13:22:54 +0800 CST2022-10-19 13:22:54 +0800 CST 2022-10-19 13:22:54 +0800 CST

创建文件夹树逻辑简化

  • 772

我刚开始学习一些 PowerShell 并迈出第一步。我正在训练创建目录。

我在下面编写了这段代码,但我想问一下如何进一步简化它并帮助我继续学习和扩展我的 PowerShell 技能?

$branch1 = (@('Fox','Wolf','Cat','Cow','Snake','Elephant') | ForEach-Object { New-Item (Join-Path 'C:\tree\Animals\' $_) -ItemType Directory -force })
$branch2 = (@('Chair','Cupboard','Sofa','Table','Bed','Dresser') | ForEach-Object { New-Item (Join-Path 'C:\tree\Furniture\' $_) -ItemType Directory -force })
$branch3 = (@('Mercury','Venus','Earth','Mars','Jupiter','Saturn') | ForEach-Object { New-Item (Join-Path 'C:\tree\Planets\' $_) -ItemType Directory -force })
$FolderTree = $branch1 + $branch2 + $branch3
if ($FolderTree) { Write-Host "All sorted out."}
windows powershell
  • 2 2 个回答
  • 55 Views

2 个回答

  • Voted
  1. Best Answer
    Vomit IT - Chunky Mess Style
    2022-10-19T19:28:04+08:002022-10-19T19:28:04+08:00

    潜在的简化调整

    1. 将数组数据类型显式设置为变量。

    2. 创建一个函数并在其中构建New-Item命令,以在执行时根据传递给函数调用的值接受两个参数,以动态构建要创建的路径。

    3. 最后,ForEach-Object遍历每个数组,显式定义函数调用的第一个参数,并让第二个参数是每个$_占位符的数组的迭代值(例如 _Main "animals" $_;)。

    注意:有些人可能也考虑使用简化%的ForEach-Object别名,所以我在下面的示例 PowerShell 中使用了它,因为您特别询问了简化。

    电源外壳

    $animals = 'Fox','Wolf','Cat','Cow','Snake','Elephant';
    $furniture = 'Chair','Cupboard','Sofa','Table','Bed','Dresser';
    $planets = 'Mercury','Venus','Earth','Mars','Jupiter','Saturn';
    
    Function _Main (){
        New-Item "C:\tree\$($args[0])\$($args[1])" -ItemType Directory -Force;
        };
    
    $animals | % { _Main "animals" $_; };
    $furniture | % { _Main "furniture" $_; };
    $planets  | % { _Main "planets" $_; };
    

    PowerShell(不同的变体)

    $animals = 'Fox','Wolf','Cat','Cow','Snake','Elephant';
    $furniture = 'Chair','Cupboard','Sofa','Table','Bed','Dresser';
    $planets = 'Mercury','Venus','Earth','Mars','Jupiter','Saturn';
    
    Function _Main (){
        New-Item "$($args[0])" -ItemType Directory -Force;
        };
    
    $animals | % { _Main "C:\tree\animals\$_"; };
    $furniture | % { _Main "C:\tree\furniture\$_"; };
    $planets  | % { _Main "C:\tree\planets\$_"; };
    

    支持资源

    • PowerShell 函数

      最基本的函数就是 function 关键字,后跟函数的名称,然后是一对花括号内的一些代码。

      function Add-Numbers {  $args[0] + $args[1] }
      
      PS C:\> Add-Numbers 5 10 
      15
      
    • about_Functions

    • PowerShell 运算符 $( ) @( ) :: &

    • ForEach-对象

      Foreach-Object 的标准别名%:' ' 符号,ForEach

    • 1
  2. swbbl
    2022-10-19T20:52:58+08:002022-10-19T20:52:58+08:00

    这是@Vomit IT - Chunky Mess Style 的有用方法的替代方法。

    这种方法使用哈希表并验证New-Item. 它在结构、动态和可读性方面得到了简化。不是单行/更少的代码。

    $basePath = 'C:\tree\'
    
    # a hashtable with a key and value pair
    # the key or value could also be a path, see example 'Food\Vegetables' below
    $directoryTree = @{
        # Key         = Value(s)
        Animals       = 'Fox', 'Wolf', 'Cat', 'Cow', 'Snake', 'Elephant'
        Furniture     = 'Chair', 'Cupboard', 'Sofa', 'Table', 'Bed', 'Dresser'
        Planets       = 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn'
        'Food\Fruits' = 'Berries\Banana', 'Berries\Watermelon', 'Apple', 'Pineapple'
    }
    
    # reset error indicator of New-Item
    $newItemCommandError = $null
    
    # loop through the keys. Always use ".psbase." to avoid the hashtable property "Keys" gets overriden by a key named "Keys"
    foreach ($directory in $directoryTree.psbase.Keys) {
        # loop through the values of current key
        foreach ($subDirectory in $directoryTree[$directory]) {
            # build full path by concatenating Join-Path via Pipe(s).
            # can be simplified as of PS7+: "Join-Path $basePath $directory $subDirectory"
            $fullPath = Join-Path $basePath $directory | Join-Path -ChildPath $subDirectory
            # ErrorVariable +'newItemCommandError' acts as an indicator for errors
            $null = New-Item $fullPath -ItemType Directory -Force -ErrorVariable +'newItemCommandError'
        }
    }
    
    if (-not $newItemCommandError) {
        Write-Host 'All sorted out.'
    }
    

    没有注释和结果的相同代码:

    $basePath = 'C:\tree\'
    $directoryTree = @{
        Animals   = 'Fox', 'Wolf', 'Cat', 'Cow', 'Snake', 'Elephant'
        Furniture = 'Chair', 'Cupboard', 'Sofa', 'Table', 'Bed', 'Dresser'
        Planets   = 'Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn'
    }
    
    $newItemCommandError = $null
    foreach ($directory in $directoryTree.psbase.Keys) {
        foreach ($subDirectory in $directoryTree[$directory]) {
            $fullPath = Join-Path $basePath $directory | Join-Path -ChildPath $subDirectory
            $null     = New-Item $fullPath -ItemType Directory -Force -ErrorVariable +'newItemCommandError'
        }
    }
    
    if (-not $newItemCommandError) {
        Write-Host 'All sorted out.'
    }
    
    • 1

相关问题

  • Python 的“pass”参数的批处理等价物是什么?

  • 禁用后无法启用 Microsoft Print to PDF

  • 我可以让这个 PowerShell 脚本接受逗号吗?

  • 在 Windows 上与 Docker 守护进程通信

  • 资源管理器侧面板中的桌面外壳快捷方式

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    如何减少“vmmem”进程的消耗?

    • 11 个回答
  • Marko Smith

    从 Microsoft Stream 下载视频

    • 4 个回答
  • Marko Smith

    Google Chrome DevTools 无法解析 SourceMap:chrome-extension

    • 6 个回答
  • Marko Smith

    Windows 照片查看器因为内存不足而无法运行?

    • 5 个回答
  • Marko Smith

    支持结束后如何激活 WindowsXP?

    • 6 个回答
  • Marko Smith

    远程桌面间歇性冻结

    • 7 个回答
  • Marko Smith

    子网掩码 /32 是什么意思?

    • 6 个回答
  • Marko Smith

    鼠标指针在 Windows 中按下的箭头键上移动?

    • 1 个回答
  • Marko Smith

    VirtualBox 无法以 VERR_NEM_VM_CREATE_FAILED 启动

    • 8 个回答
  • Marko Smith

    应用程序不会出现在 MacBook 的摄像头和麦克风隐私设置中

    • 5 个回答
  • Martin Hope
    Saaru Lindestøkke 为什么使用 Python 的 tar 库时 tar.xz 文件比 macOS tar 小 15 倍? 2021-03-14 09:37:48 +0800 CST
  • Martin Hope
    CiaranWelsh 如何减少“vmmem”进程的消耗? 2020-06-10 02:06:58 +0800 CST
  • Martin Hope
    Jim Windows 10 搜索未加载,显示空白窗口 2020-02-06 03:28:26 +0800 CST
  • Martin Hope
    v15 为什么通过电缆(同轴电缆)的千兆位/秒 Internet 连接不能像光纤一样提供对称速度? 2020-01-25 08:53:31 +0800 CST
  • Martin Hope
    andre_ss6 远程桌面间歇性冻结 2019-09-11 12:56:40 +0800 CST
  • Martin Hope
    Riley Carney 为什么在 URL 后面加一个点会删除登录信息? 2019-08-06 10:59:24 +0800 CST
  • Martin Hope
    zdimension 鼠标指针在 Windows 中按下的箭头键上移动? 2019-08-04 06:39:57 +0800 CST
  • Martin Hope
    jonsca 我所有的 Firefox 附加组件突然被禁用了,我该如何重新启用它们? 2019-05-04 17:58:52 +0800 CST
  • Martin Hope
    MCK 是否可以使用文本创建二维码? 2019-04-02 06:32:14 +0800 CST
  • Martin Hope
    SoniEx2 更改 git init 默认分支名称 2019-04-01 06:16:56 +0800 CST

热门标签

windows-10 linux windows microsoft-excel networking ubuntu worksheet-function bash command-line hard-drive

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve