如何在PowerShell中正确拆分字符串

wnavrhmk  于 2022-11-10  发布在  Shell
关注(0)|答案(2)|浏览(192)

我有这根绳子

"C:\Users\testinguser\OneDrive - Company\Desktop\Hello\Jobs\Testing-Online\_vti_history\101376\Shared Documents\Global PKI\Legacy Stuff\Vehicle Credential Trackers\Tracker_JLN_records_USE.xlsx"

我只是在想,我怎么才能离开,只有这样才能得到结果

vti_history\101376\Shared Documents\Global JLN\Legacy Stuff\Vehicle Credential Trackers\Tracker_JLN_records_USE.xlsx

我试过使用-Split(“_”),但不起作用。

$Path = "C:\Users\testinguser\OneDrive - Company\Desktop\Hello\Jobs\Testing-Online\_vti_history\101376\Shared Documents\Global JLN\Legacy Stuff\Vehicle Credential Trackers\Tracker_JLN_records_USE.xlsx"

$Result = $Path -split('\_')[2]

任何帮助或建议都将不胜感激。

mm9b1k5b

mm9b1k5b1#

你可以做到的

$myString = "C:\Users\testinguser\OneDrive - Company\Desktop\Hello\Jobs\Testing-Online\_vti_history\101376\Shared Documents\Global PKI\Legacy Stuff\Vehicle Credential Trackers\Tracker_JLN_records_USE.xlsx" -split "(\\_)"
Write-Output $myString[2]

输出:vti_history\101376\Shared Documents\Global PKI\Legacy Stuff\Vehicle Credential Trackers\Tracker_JLN_records_USE.xlsx

dhxwm5r4

dhxwm5r42#

有几件事是错的。由于[2]的运算符优先级较高,您在$NULL上拆分,因为(‘_’)只有2个字符。括号是不必要的,但没有坏处,因为拆分不是一个函数。在'\_'上拆分会产生正则表达式解析错误,因此必须转义反斜杠。对'(\\_)'进行拆分,并将括号放在引号内,将在结果中包括分隔符。

$Path = 'C:\Users\testinguser\OneDrive - Company\Desktop\Hello\Jobs\Testing-Online\_vti_history\101376\Shared Documents\Global JLN\Legacy Stuff\Vehicle Credential Trackers\Tracker_JLN_records_USE.xlsx'

($Path -split '\\_')[1]

vti_history\101376\Shared Documents\Global JLN\Legacy Stuff\Vehicle Credential Trackers\Tracker_JLN_records_USE.xlsx

$Path -split '\_'

parsing "\_" - Unrecognized escape sequence \_.
At line:1 char:1
+ $Path -split '\_'
+ ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException

$Path -split '(\\_)'

C:\Users\testinguser\OneDrive - Company\Desktop\Hello\Jobs\Testing-Online
\_
vti_history\101376\Shared Documents\Global JLN\Legacy Stuff\Vehicle Credential Trackers\Tracker_JLN_records_USE.xlsx

'\_'[2] -eq $null

True

在字符串数组是第一个参数(而不是字符数组)的情况下,您可以使用字符串拆分.Net函数重载之一,但它需要第二个参数。这样您就不必担心如何转义正则表达式字符。使用单个字符分隔符会更容易。


# string[] Split(string[] separator, System.StringSplitOptions options)

$path.split([string[]]'\_','None')

# $path.split((,'\_'),0)

C:\Users\testinguser\OneDrive - Company\Desktop\Hello\Jobs\Testing-Online
vti_history\101376\Shared Documents\Global JLN\Legacy Stuff\Vehicle Credential Trackers\Tracker_JLN_records_USE.xlsx

查看所有重载:

$path.split

OverloadDefinitions
-------------------
string[] Split(Params char[] separator)
string[] Split(char[] separator, int count)
string[] Split(char[] separator, System.StringSplitOptions options)
string[] Split(char[] separator, int count, System.StringSplitOptions options)
string[] Split(string[] separator, System.StringSplitOptions options)
string[] Split(string[] separator, int count, System.StringSplitOptions options)

相关问题