Add-Content String Quotes with Variable - powershell

I am tring to add a line to a text file I created however it needs to contain text quotes around a variable.
An example I am working with:
$wksname="wks12345"
$path = c:\scripts\file.txt
Add-Content $path '"DefaultUsername" =' "$wksname"
I get an error stating that a positional parameter is not found.
What I would like the output to look like in the text file is:
"DefaultUsername" = "wks12345"
Any ideas?
Thanks!

Use two consecutive " as an escape sequence:
Add-Content $path """DefaultUsername"" = ""$wksname"""

Use the escape char `
$wksname = "TEST123"
write-host "`"DefaultUsername`" = `"$wksname`""
Would wrote out "DefaultUsername" = "TEST123"
As for the command it should look like
$wksname="wks12345"
$path = "c:\scripts\file.txt"
Add-Content -Path $path -Value "`"DefaultUsername`" = `"$wksname`""

Your string quoting is wrong. Here's your command:
Add-Content $path '"DefaultUsername" =' "$wksname"
You've got three parameters:
$path
'"DefaultUsername" ='
"$wksname"
And Add-Content only has 2 positional parameters (-Path and -Value). PowerShell can't find a third parameter to use.
If you need to use double quotes in a string and you also want to expand variables in your string, you need to escape your double quotes. There's two ways to do it.
Like this:
Add-Content -Path $path -Value """DefaultUsername"" = ""$wksname"""
Or this:
Add-Content -Path $path -Value "`"DefaultUsername`" = `"$wksname`""

Related

PowerShell - How to Concatenate variable with text? on same line on text file

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
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)"
"*" 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"

Powershell dot-sourcing variables inside variables not expanding

I've got the following problem:
Say I have 2 powershell scripts, named A.ps1 and conf.ps1.
conf.ps1 contents are just a few vars that will be dot-sourced by A.ps1, like this:
$dateLogs = Get-Date -UFormat '%Y%m%d'
$installDir = 'C:\Gcloud\'
$logDir = '$installDir\GcloudLogs'
$logFile = '$logDir\$dateLogs\logFile.txt'
When imported, funny thing is that $dateLogs is expanded and in the debugger I can see "..\20190805\logFile.txt" but $installDir, for some reason, won't expand.
So instead of having $logFile = "C:\Gcloud\GcloudLogs\20190805\logFile.txt" I end up having "$installDir\GcloudLogs\20190805\logFile.txt"and that $installDir won't ever expand to its real value.
Am I missing something?
Any lead would be much appreciatd since I've been struggling for a long time with this. I tried several things like:
- ${$installDir}\GcloudLogs
- $($installDir\GcloudLogs)
- $(${installDir}\GcloudLogs)
With single quotes, double quotes and no quotes at all... None of that worked out.
Thank you all beforehand.
In order to not confuse single or double quotes and to save you from getting paths with double backslashes, it is always safer to use the Join-Path cmdlet.
$dateLogs = '{0:yyyyMMdd}' -f (Get-Date) # a more 'PowerShelly' way of formatting a date
$installDir = 'C:\Gcloud'
$logDir = Join-Path -Path $installDir -ChildPath 'GcloudLogs'
$logFile = Join-Path -Path $logDir -ChildPath "$dateLogs\logFile.txt" # use double-quotes here
It is also possible to use the .NET [System.IO.Path]::Combine() function
$dateLogs = '{0:yyyyMMdd}' -f (Get-Date)
$installDir = 'C:\Gcloud'
$logDir = [System.IO.Path]::Combine($installDir, "GcloudLogs")
$logFile = [System.IO.Path]::Combine($logDir, $dateLogs, "logFile.txt")
Both methods will create these paths:
$logDir --> C:\Gcloud\GcloudLogs
$logFile --> C:\Gcloud\GcloudLogs\20190805\logFile.txt
There's a difference between single and double quotes in string constants in Powershell. Try using double quotes instead.

How to properly use -Exclude in Remove-Item for a list of string from a variable in Powershell?

I have a variable that stored the list of files to be removed in this format:
$list = """" + "file1.txt" + """"
and a complete $list would be looking something like this:
$list
"file1.txt","file2.txt","file3.txt",...
and trying to use Remove-Item with the variable failed, it removed all the files:
Remove-Item -Recurse -Path "c:\myfiles\*" -Exclude $list
How to properly achieve this? Thanks in advance!
You're close but $list needs to be an array not a string (with excess quotes).
Just quote each element, and separate them with a comma to do this:
$list = "file1.txt","file2.txt"
Remove-Item -Path "c:\myfiles\*" -Recurse -Exclude $list -WhatIf
I would also recommend reading about_quoting_rules as it seems you don't know that double and single quotes do different things.
Using single quotes instead:
$list = """" + "file1.txt" + """"
can be expressed as:
$list = '"file1.txt"'
(These extra quotes aren't needed for the code above)

Extract the filename from a path

I want to extract filename from below path:
D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv
Now I wrote this code to get filename. This working fine as long as the folder level didn't change. But in case the folder level has been changed, this code need to rewrite. I looking a way to make it more flexible such as the code can always extract filename regardless of the folder level.
($outputFile).split('\')[9].substring(0)
If you are ok with including the extension this should do what you want.
$outputPath = "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
$outputFile = Split-Path $outputPath -leaf
Use .net:
[System.IO.Path]::GetFileName("c:\foo.txt") returns foo.txt.
[System.IO.Path]::GetFileNameWithoutExtension("c:\foo.txt") returns foo
Using the BaseName in Get-ChildItem displays the name of the file and and using Name displays the file name with the extension.
$filepath = Get-ChildItem "E:\Test\Basic-English-Grammar-1.pdf"
$filepath.BaseName
Basic-English-Grammar-1
$filepath.Name
Basic-English-Grammar-1.pdf
Find a file using a wildcard and get the filename:
Resolve-Path "Package.1.0.191.*.zip" | Split-Path -leaf
$(Split-Path "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv" -leaf)
Get-ChildItem "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
|Select-Object -ExpandProperty Name
You could get the result you want like this.
$file = "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
$a = $file.Split("\")
$index = $a.count - 1
$a.GetValue($index)
If you use "Get-ChildItem" to get the "fullname", you could also use "name" to just get the name of the file.
Just to complete the answer above that use .Net.
In this code the path is stored in the %1 argument (which is written in the registry under quote that are escaped: \"%1\" ). To retrieve it, we need the $arg (inbuilt arg). Don't forget the quote around $FilePath.
# Get the File path:
$FilePath = $args
Write-Host "FilePath: " $FilePath
# Get the complete file name:
$file_name_complete = [System.IO.Path]::GetFileName("$FilePath")
Write-Host "fileNameFull :" $file_name_complete
# Get File Name Without Extension:
$fileNameOnly = [System.IO.Path]::GetFileNameWithoutExtension("$FilePath")
Write-Host "fileNameOnly :" $fileNameOnly
# Get the Extension:
$fileExtensionOnly = [System.IO.Path]::GetExtension("$FilePath")
Write-Host "fileExtensionOnly :" $fileExtensionOnly
You can try this:
[System.IO.FileInfo]$path = "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
# Returns name and extension
$path.Name
# Returns just name
$path.BaseName
$file = Get-Item -Path "c:/foo/foobar.txt"
$file.Name
Works with both relative and absolute paths

illegal characters in path using powershell

I need to verify one path using powershell. The problem is when given the path like Test-Path -Path "\\\10.2.200.13\share\Logger\Logger" its working fine, but my requirement is that, this path will be available in a Notepad - we need to read the path from the notepad then verify it. Here is the code:
$var = ( Get-Content D:\TestPathIssue\Params.txt ) -split '='
$source1=$var[1].Trim();
test-path -Path $source1;
I am able to get path in $source1 but I don't understand why its failing in Test-Path in this approach.
Fixed by trying this-
$source1=$source1 -replace '"', ""
Check if the variable $source1 is returning path in quotes eg:- "\10.2.200.13\share\Logger\Logger" instead of \10.2.200.13\share\Logger\Logger
The following powershell code will take a list of legal characters with regex and report back on any non-legal characters found in filenames. Modify the list of legal characters as desired.
$legal = "[a-zA-Z\d\.\-'_\s\(\)&,%\[\];\!\$\+#~=#]"
ForEach ($File in Get-ChildItem -Path C:\mypath -Recurse){
ForEach ($char in $File.Name.ToCharArray()){
If ($char -notmatch $legal){
$output = $char+" found in "+$file.fullname
write-output $output
break
}
}
}