簡體   English   中英

如果存在傳遞的字符串中,則Invoke-Expression命令將替換$

[英]Invoke-Expression command is replacing $ if exisiting into string passed

我正在執行一個帶有一個字符串參數的ps1文件。 字符串參數本身包含$。 與特定字母組合后,它將其視為變量。

說明:

$variableWithDolar = 'Test$Var'
$inputString = "Testing with " + "`'$variableWithDolar`'" 
$inputString = '"' + $inputString + '"'
$scriptPath="C:\test\PrintArg.ps1"
Invoke-Expression -Command "& `"$scriptPath`" $inputString"

在這里,PrintArg.ps1是一個powershell腳本,它只接受一個字符串參數並將其打印出來。

預期的輸出:“使用Test $ Var進行測試”實際的輸出:“使用Test $ Var進行測試”

由於它將$ Var視為空變量。

誰能幫助我,我將如何通過Invoke-Expression獲得預期的輸出。

一種方法是添加單引號,以防止Powershell嘗試替代$ Var。 在雙引號字符串中,Powershell將執行變量替換。 將第一行的雙引號更改為單引號,並在最后一行的$ inputString周圍添加單引號:

$variableWithDolar = 'Test$Var'
$inputString = "Testing with " + $variableWithDolar 
$scriptPath="C:\temp\PrintArg.ps1"
Invoke-Expression -Command "& `"$scriptPath`" '$inputString'"

Poweshell中的引號可能很棘手,請查看文檔以獲取完整說明: https ://technet.microsoft.com/zh-cn/library/hh847740.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM