Home > Software engineering >  PowerShell - How to Concatenate variable with text? on same line on text file
PowerShell - How to Concatenate variable with text? on same line on text file

Time:10-28

I'm having difficulties to join a text with 1 string how do I make this join without breaking line in power shell? can you help me.

I Want This:

> PlaybackDevice=AudioDevice 
> RingerDevice=AudioDevice
> RecordDevice=AudioDeviceRecord

But i have this on execute:

     PlaybackDevice= 
$audio.Name
     RingerDevice=  
$audio.Name 
     RecordDevice= 
$mic.Name

This is my code:

Add-Content "C:\burn.txt*" "RingerDevice=" $audio.Name 
Add-Content"C:\burn.txt*" "RecordDevice=" $mic.Name 
Add-Content "C:\burn.txt*" "PlaybackDevice=" $audio.Name

CodePudding user response:

try this

Add-Content "C:\burn.txt*" "RingerDevice=$($audio.Name)"
Add-Content "C:\burn.txt*" "RecordDevice=$($mic.Name)"
Add-Content "C:\burn.txt*" "PlaybackDevice=$($audio.Name)"

CodePudding user response:

"*" is not allowed in the a hard drive path. You must put ALL of content you want to write in "" or ''. Given that you have a variable such as "$audio.Name" it is treated as a object that has a label called "name" and a value called "logictech" in my example below. Add-Content only wants the value by using $() you can expand the variable and only give the value. e.g. $($audio.Name). Never write to the C:\ path. It is block in many places for security reasons. Run the code below for a working example.

$audio = [PSCustomObject]@{
    Name     = "logictech"
}

$mic= [PSCustomObject]@{
    Name     = "MyMic"
}

Add-Content -path "$env:temp\burn.txt" -Value "RingerDevice=$($audio.Name)"
Add-Content -Path "$env:temp\burn.txt" -Value  "RecordDevice=$($mic.Name)"
Add-Content -Path "$env:temp\burn.txt" "PlaybackDevice=$($audio.Name)"

sleep 10

Start-Process "$env:temp\burn.txt"
  • Related