[英]PowerShell out-file not working when variable has a “/” in filename
我有一個運行GET並將結果保存到文件的Powershell腳本。 文件名使用的是來自GET URL的變量,但是,正斜杠存在“ /”。 該文件未保存,因為它不喜歡正斜杠。
$hostURL = "my_webserver"
$methType = "GET"
$api4 = "/sasl_logs/debug"
$txt | out-file ".\$api4.txt"
結果是一個名為/sasl_logs/debug.txt或/sasl_logs_debug.txt的文件。 我試圖讓替換功能正常工作,但是我一定做錯了。
$api4.replace("//","_")
$api4.replace("/","_")
$api4.replace("\/","_")
這里的問題不是斜線。 並非您認為的那樣。 Windows(和Powershell)支持/
定界的路徑名就很好(許多/大多數其他Windows應用程序也一樣)。
這里的問題是路徑/sasl_logs/debug
被視為絕對路徑(以斜杠開頭),因此被視為C:\\sasl_logs\\debug
, Out-File
拒絕創建sasl_logs
目錄,因此它可以將debug
文件放在該位置。
創建C:\\sasl_logs
目錄,它應該可以正常工作。
如果您不想要該目錄(或者根本不希望有任何目錄),而$api4
值不是按$api4
設置的(因此您不能只是更改代碼),那么您想要的就是您嘗試的東西。
$api4 = $api4.Substring(1) -replace "/","_"
Substring
去除前導/
,然后-replace
運算符進行替換。 您當然也可以使用$api4.Substring(1).Replace("/","_")
。
從您的文章和評論,這聽起來像你最終問如何成功地取代“/”字符...
$api4 = "/sasl_logs/debug"
$api4 = $api4.Replace("/","_")
好的,這很好,謝謝Etan Reisner
$txt | out-file ".\$api.txt".Replace("/","_")
創建一個名為
_sasl_logs_debug.txt
正在領導_工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.