当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] PowerShell 将路径拆分为数组

作者:精品下载站 日期:2024-12-14 16:48:10 浏览:12 分类:玩电脑

PowerShell 将路径拆分为数组


要在 PowerShell 中将路径拆分为数组,请使用 PowerShell String Split() 函数或 split 运算符。目录路径由字符反斜杠\)分隔,使用反斜杠作为分隔符,将目录路径分解为字符串数组。

在本文中,我们将讨论使用 PowerShell 字符串 Split() 函数和拆分运算符将路径拆分为数组。

在 PowerShell 中使用 Split() 将路径拆分为数组

使用 PowerShell String 内置 Split() 函数将路径拆分为数组。

参考以下步骤在PowerShell中将路径拆分成数组

  1. 在 PowerShell 中声明一个字符串并将其存储在变量中。
  2. 对变量调用 PowerShell Split() 字符串方法。
  3. 使用反斜杠 (\) 字符作为分隔符将字符串分解为数组。
$path = "C:\Windows\System32\calc.exe" 

# Use the backslash as delimiter to splits the string into array
$path.Split("\") 

在上面的PowerShell脚本中,PowerShell字符串Split()函数使用反斜杠作为分隔符将路径拆分为字符串数组。

将路径获取到数组的上述脚本的输出是:

PS C:\> $path = "C:\Windows\System32\calc.exe"  

PS C:\> $path.Split("\")                                                                                                

C:
Windows
System32
calc.exe
PS C:\>  

使用 Split 运算符将目录路径拆分为数组

您可以使用 PowerShell 拆分运算符将目录路径拆分为数组。在分割运算符中使用反斜杠 (\) 字符将路径分解为字符串数组。

请参考以下步骤,在PowerShell中使用拆分运算符将路径拆分为数组

  1. 在 PowerShell 中声明一个字符串并将其存储在变量中。
  2. 对变量使用 PowerShell split 运算符
  3. 使用反斜杠 (\\) 字符作为分隔符将路径分解为字符串数组
$dirpath = "D:\PS\Alias.txt" 

# use the split operator and pass \ as delimiter
$dirpath -split '\' 

在 PowerShell 脚本中,拆分运算符使用反斜杠字符将路径拆分为数组。

将路径分解为字符串数组后,上述 PowerShell 脚本的输出为:

PS C:\> $dirpath = "D:\PS\Alias.txt"                                                                                    

PS C:\> $dirpath -split '\'                                                                                            
D:
PS
Alias.txt

PS C:\>                                                                                                                                

酷提示:如何在PowerShell中使用GetEnumerator读取数组数据!

结论

希望上面关于如何使用PowerShell字符串Split()方法和拆分运算符将路径拆分为数组的文章对您有所帮助。

您可以在 ShellGeek 主页上找到有关 PowerShell Active Directory 命令和 PowerShell 基础知识的更多主题。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯