Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell,在解析和切换目录名称的字符串后重命名目录_Powershell_Foreach_Split_Get Childitem_Rename Item Cmdlet - Fatal编程技术网

Powershell,在解析和切换目录名称的字符串后重命名目录

Powershell,在解析和切换目录名称的字符串后重命名目录,powershell,foreach,split,get-childitem,rename-item-cmdlet,Powershell,Foreach,Split,Get Childitem,Rename Item Cmdlet,因此,我尝试将几个level1子文件夹从“xy_1234”重命名为“1234_xy”。到目前为止,我已经实现了将字符串拆分为变量、构建新的目录名和重命名目录,但是当我尝试在for循环中自动化该过程时,我完全失败了。请帮忙 Get-Item $Path | ForEach ( $a, $b = $Path.split('_') | Rename-Item -NewName { $b + ('_') + $a}) -WhatIf预览操作 如您所见,您可以将解析作为传递给Rename Item的-N

因此,我尝试将几个level1子文件夹从“xy_1234”重命名为“1234_xy”。到目前为止,我已经实现了将字符串拆分为变量、构建新的目录名和重命名目录,但是当我尝试在for循环中自动化该过程时,我完全失败了。请帮忙

Get-Item $Path | ForEach ( $a, $b = $Path.split('_') | Rename-Item -NewName { $b + ('_') + $a})
-WhatIf
预览操作

如您所见,您可以将解析作为传递给
Rename Item
-NewName
参数的脚本块的一部分进行

由于
-NewName
只需要项的文件或目录的新名称(与完整路径相反),因此将解析
$\uName
,并(隐式)输出它的转换

以下是一个更简洁的公式,灵感来自:

这依赖于PowerShell通过指定索引数组(列表)对数组进行切片的能力:
-1,1,0
有效地反转
$\u.Name-split'(\u)
返回的数组元素-请注意
(…)
周围的
,它确保
\uuu
的实例包含在返回的令牌数组中;然后,
-join
运算符的一元形式连接反向数组的元素


注意:我假设
$Path
包含一个只匹配感兴趣目录的通配符表达式

若您只需要明确匹配目录,请使用
getchilditem

-目录
开关:

Get-ChildItem $Path -Directory
使用通配符模式专门匹配您问题中的示例名称:

Get-ChildItem [a-z][a-z]_[0-9][0-9][0-9][0-9] -Directory

我认为应该使用GCI捕获多个子文件夹
将“xy_1234”转换为“1234_xy”文字:

可能重复的
Get-ChildItem $Path -Directory
Get-ChildItem [a-z][a-z]_[0-9][0-9][0-9][0-9] -Directory
Get-ChildItem $Path -Dir | Where-Object Name -match '^([a-z]+)_(\d+)$' |
    Rename-Item -NewName {$_.Name.Split('_')[1,0] -join ('_')} -WhatIf