rcmpayne
rcmpayne

Reputation: 163

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("\/","_")

Upvotes: 0

Views: 1532

Answers (3)

rcmpayne
rcmpayne

Reputation: 163

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

Upvotes: 0

Etan Reisner
Etan Reisner

Reputation: 81022

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.

Upvotes: 1

Samuel Prout
Samuel Prout

Reputation: 665

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("/","_")

Upvotes: 0

Related Questions