もっと詳しく

PowerShell 文字列 スプリット() 関数は、指定された区切り記号に基づいて文字列を複数の部分文字列に分割します。 文字列の改行で分割するには、Split() メソッドを使用できます [Environment::Newline].

CRLF 行区切り記号を含む文字列またはテキスト ファイルがある場合は、PowerShell 文字列分割メソッドまたは分割演算子を使用できます。

この記事では、特定の文字列またはテキスト ファイルを新しい行で分割する方法について説明します。 Split() メソッドまたは分割演算子.

文字列の改行でPowerShell分割

複数行の文字列を含む文字列があり、新しい行で分割したい場合は、PowerShell 文字列を使用して簡単に行うことができます スプリット() 方法。

$testString = "Welcome to `r`nShellGeek Website"

#Split on new line using Environment::NewLine
$testString.Split([System.Environment]::NewLine,[System.StringSplitOptions]::RemoveEmptyEntries)   

上記の PowerShell スクリプトでは、 $testString を持つ文字列が含まれています CRLF (キャリッジ リターンとライン フィード)。

PowerShell 文字列 Split() メソッドを使用して、 [Environment]::改行 新しい行で文字列を分割する区切り文字として。

StringSplitOptions::RemoveEmptyEntries はオプションのパラメータで、空のエントリを結果から削除します。

split() メソッドを使用した後の上記の PowerShell スクリプトの出力

Welcome to
ShellGeek Website

また、 スプリット の助けを借りて改行で文字列を分割する演算子 [Environment]::改行または `r`n

$testString = "Welcome to `r`nShellGeek Website" 

# Split the newline using `r`n
$teststring -split "`r`n" 

# Split the newline using Environment::NewLine
$teststring -split [System.Environment]::NewLine  

上記の PowerShell スクリプトでは、Environment::NewLine または `r`n を使用して文字列を改行で分割する方法をいくつか使用しました。

改行で文字列を分割した後の上記のスクリプトの出力は次のとおりです。

Welcome to
ShellGeek Website

PowerShellは改行でテキストファイルを分割します

を使用できます。 取得コンテンツ PowerShell のコマンドレットを使用して、テキスト ファイルを改行で分割します。 Get-Content コマンドは、既定で新しい行に分割され、文字列配列を返します。

(Get-Content -Path D:PSAlias.txt)   

上記の PowerShell スクリプトでは、 取得コンテンツ コマンドレットは、Path パラメーターを使用して、ファイルの名前とそのパスを指定します。 デフォルトでは、コンテンツを読み取り、改行で分割します。

テキスト ファイルを新しい行に分割した後の上記の PowerShell スクリプトの出力は次のとおりです。

PS C:> (Get-Content -Path D:PSAlias.txt)                                                                             # Alias File
# Exported by : ShellGeek
# Date/Time : 30 July 2022 18:57:47
# Computer : INCORP-EU-117
"foreach","ForEach-Object","","ReadOnly, AllScope"
"%","ForEach-Object","","ReadOnly, AllScope"
"where","Where-Object","","ReadOnly, AllScope"
"?","Where-Object","","ReadOnly, AllScope"
"ac","Add-Content","","ReadOnly, AllScope"
"clc","Clear-Content","","ReadOnly, AllScope"

PowerShell string Split() メソッドを使用して、テキスト ファイルを新しい行に分割することもできます。 [Environment]:: NewLine を取得し、文字列配列を返します。

# Using the Split method to split the text file on new line
(Get-Content -Path D:PSAlias.txt).Split([System.Environment]::NewLine)

# Using the Split operator to split the file on newline
(Get-Content -Path D:PSAlias.txt -Raw) -split "`r`n"

結論

改行で文字列を分割する方法、または改行でテキスト ファイルを分割する方法に関する上記の記事がお役に立てば幸いです。

PowerShell Active Directory コマンドと PowerShell の基本に関するその他のトピックについては、ShellGeek のホームページを参照してください。

The post NewLine での PowerShell 分割 – ShellGeek appeared first on Gamingsym Japan.