[英]powershell out-file how to rid of extra spaces on each line
我運行此命令,並在names.txt文件中獲得了所有計算機的主機名。 文件中的每個主機名都位於單獨的行中,但是每個主機名后都帶有空格,這在我嘗試讀取此文件時會引起問題。 如何在不獲取每行空白的情況下輸出到此文件?
Get-ADComputer -Filter * | Select-Object -property name | Sort-Object -Property name | out-file -filepath C:\temp\names.txt
您會遇到這樣的問題:您不僅擁有名稱,還擁有帶有“名稱”屬性的對象,並且還存在Out-File
在將復雜對象發送到文件之前通過某種格式運行它們的問題。
要同時解決這兩個問題,請將名稱擴展為僅文本,通常使用Set-Content
:
Get-ADComputer -filter * | Select-Object -ExpandProperty Name | Sort-Object | Set-Content C:\temp\names.txt
或簡寫形式
Get-ADComputer -filter * | Select -Expand Name | Sort | sc C:\temp\names.txt
要么
(Get-ADComputer -filter *).Name | sort | sc C:\temp\names.txt
通過它進行配管應該起作用(在配管到外文件之前):
編輯 :通過% { $_.name }
配管應將@ {name = VALUE}轉換為VALUE:
% { $_ -replace ' +$','' } | % { $_.name }
像這樣:
Get-ADComputer -Filter * | Select-Object -property name | Sort-Object -Property name | % { $_ -replace ' +$','' } | % { $_.name } | out-file -filepath C:\temp\names.txt
expandproperty應該擺脫@()
Get-ADComputer -Filter * | sort Name | Select -expandproperty Name | %{ $_.TrimEnd(" ") } | out-file -filepath C:\temp\names
未經測試沒有AD @ home
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.