简体   繁体   中英

PowerShell out-file not working when variable has a “/” in filename

I have a powershell script that is running a GET and saving the results to file. the name of the file is using a variable from the GET URL however, then a forward slash exist "/". the file is not saved because it does not like the forward slash.

$hostURL = "my_webserver"
$methType = "GET"
$api4 = "/sasl_logs/debug"
$txt | out-file ".\$api4.txt"

Results is a file called /sasl_logs/debug.txt or /sasl_logs_debug.txt. I have tried to get replace function working but i must be doing something wrong.

$api4.replace("//","_")
$api4.replace("/","_")
$api4.replace("\/","_")

The problem here is not the slash. Not in the way you think it is. Windows (and powershell) support / delimited path names just fine (as do many/most other Windows applications).

The problem here is that the path /sasl_logs/debug is being seen as an absolutel path (it starts with a slash) and so is being seen as C:\\sasl_logs\\debug and Out-File refuses to create the sasl_logs directory so it can put the debug file in that location.

Create the C:\\sasl_logs directory and it should work correctly.

If you don't want that directory (or indeed any directory at all) and the $api4 value isn't being set literally like that (so you can't just change the code) then you want something like what you were attempting.

$api4 = $api4.Substring(1) -replace "/","_"

Substring strips off the leading / and the -replace operator does the replacement. You could also use $api4.Substring(1).Replace("/","_") of course.

From your post and your comments, it sounds like you're ultimately asking how to successfully replace the "/" character...

$api4 = "/sasl_logs/debug"
$api4 = $api4.Replace("/","_")

Ok this is working, Thanks Etan Reisner

$txt | out-file ".\$api.txt".Replace("/","_")

Creates a file called

_sasl_logs_debug.txt

working on the leading _ now

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM