Umesh Pithiya
Umesh Pithiya

Reputation: 28

Not able to append variable name and content as a string in file using powershell?

This is the code for creating file and append content into it.I want to print file content as it is return below.Please give some example how to print variable name with $ si

New-Item 2.bat -type file -force -value "'
$passwd='Umesh_Pithiya' `r`n
$pass=$passwd.substring(9) `r`n
$pass=$pass.substring(1,$pass.length-2) `r`n
$pass=convertto-securestring $pass -asplaintext -force `r`n
"

Output is like this

'
='Umesh_Pithiya' 

=.substring(9) 

=.substring(1,.length-2) 

=convertto-securestring  -asplaintext -force

But I want content in file like this

$passwd='Umesh_Pithiya'
$pass=$passwd.substring(9)
$pass=$pass.substring(1,$pass.length-2)
$pass=convertto-securestring $pass -asplaintext -force
'

Upvotes: 0

Views: 104

Answers (2)

Sean
Sean

Reputation: 62472

You can use a here string:

New-Item 2.bat -type file -force -value @'
$passwd='Umesh_Pithiya'
$pass=$passwd.substring(9)
$pass=$pass.substring(1,$pass.length-2)
$pass=convertto-securestring $pass -asplaintext -force
'@

Note that you don't need to escape the carriage return and line feeds now. Also, use the single quote to avoid variable expansion.

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

' instead of " to create a verbatim string. Construct it as a here-string @''@ to avoid the single-quotes inside the text terminating the string:

New-Item 2.bat -type file -force -value @'
$passwd='Umesh_Pithiya' 
$pass=$passwd.substring(9) 
$pass=$pass.substring(1,$pass.length-2) 
$pass=convertto-securestring $pass -asplaintext -force 
'@

Upvotes: 2

Related Questions