[英]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. 我有一个运行GET并将结果保存到文件的Powershell脚本。 the name of the file is using a variable from the GET URL however, then a forward slash exist "/".
文件名使用的是来自GET URL的变量,但是,正斜杠存在“ /”。 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. 结果是一个名为/sasl_logs/debug.txt或/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). Windows(和Powershell)支持
/
定界的路径名就很好(许多/大多数其他Windows应用程序也一样)。
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. 这里的问题是路径
/sasl_logs/debug
被视为绝对路径(以斜杠开头),因此被视为C:\\sasl_logs\\debug
, Out-File
拒绝创建sasl_logs
目录,因此它可以将debug
文件放在该位置。
Create the C:\\sasl_logs
directory and it should work correctly. 创建
C:\\sasl_logs
目录,它应该可以正常工作。
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
设置的(因此您不能只是更改代码),那么您想要的就是您尝试的东西。
$api4 = $api4.Substring(1) -replace "/","_"
Substring
strips off the leading /
and the -replace
operator does the replacement. Substring
去除前导/
,然后-replace
运算符进行替换。 You could also use $api4.Substring(1).Replace("/","_")
of course. 您当然也可以使用
$api4.Substring(1).Replace("/","_")
。
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 好的,这很好,谢谢Etan Reisner
$txt | out-file ".\$api.txt".Replace("/","_")
Creates a file called 创建一个名为
_sasl_logs_debug.txt
working on the leading _ now 正在领导_工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.