如何通过PowerShell命令行从字符串中删除特殊字符

4nkexdtk  于 2023-04-12  发布在  Shell
关注(0)|答案(3)|浏览(205)

我在企业调度程序(Tidal)中调用powershell命令行,以便剥离特殊字符,并最终将其放入文件。我需要在转储到文件之前剥离特殊字符,因为后处理脚本无法容忍它们。
我现在拥有的看起来像这样:

powershell.exe $content1 = "< JobOutput >"; $content1 = $content1 -replace (['\W'],'') | out-file c:\somefile.txt

< JobOutPut >(〈〉中没有空格)是转储数据的应用程序变量,它可以包含任何类型的字符。
错误消息如下所示:

+ ...  ; $content1 = $content1 -replace ([\W],) |  ...
+                                         ~
Missing type name after '['.
At line:1 char:2324
+ ...  ; $content1 = $content1 -replace ([\W],) | Out- ...
+                                            ~
Missing argument in parameter list.

我已经尝试了它的变体,似乎有些东西需要转义,但是语法让我困惑。谢谢大家的任何想法。

ohtdti5x

ohtdti5x1#

方括号是什么意思?当你使用一个特殊的字符类,比如\W,你不需要方括号;但是即使你使用它们,它们也属于字符串。否则,PowerShell需要一个类型表达式,尽管在你的例子中,它看起来更像是你试图使用其他语言的列表/数组语法。
这工作得很好:

$content1 -replace '\W', ''

就像这样:

$content1 -replace '[\W]', ''

这两个函数都从示例字符串中生成结果JobOutput

uurv41yg

uurv41yg2#

谢谢,伙计们,我确实试过这种变奏

$content1 = $content1 -replace ('\W')

但它导致了一个错误:

\W : The term '\W' is not recognized as the name of a cmdlet, function, script file, or operable 
program. Check the spelling of the name, or if a path was included, verify that the path is 
correct and try again.
At line:1 char:2320
+ ...  ; $content1 = $content1 -replace (\W) | Out- ...
+                                        ~~

它似乎在执行的时候掉了'。

q3qa4bjr

q3qa4bjr3#

好了,我把这个问题解决了。它需要有一个完整的上下文命令行,像这样:

powershell.exe -Command "$content1 = '<JobOutput>' ; $content1 = $content1 -replace 'a','b' -replace 'c','d' ; out-file c:\somefile.txt"

这对大多数字符都有效,只有替换双引号和反斜杠有问题。其他的一切都可以用转义字符来管理。

相关问题