I am trying to find and replace a strings in a file and then saving it to the original file in PowerShell.
I've tried doing
(Get-Content "C:\Users\anon\Desktop\test.txt")
-replace 'apple', 'apple1'
-replace 'bear' , 'bear1' |
Out-File test1.txt
pause
However, I keep getting
-replace : The term '-replace' 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 C:\Users\Xing Chen\Desktop\test.ps1:2 char:1
+ -replace 'apple', 'apple1'
+ ~~~~~~~~
+ CategoryInfo : ObjectNotFound: (-replace:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
I've been able to use "abcd".replace() fine and according to the documentation -replace should work too.
There is nothing in your code to represent the line continuations and the interpreter is not seeing the -replace operators as part of the same command. You have two options to resolve this: escaping the newlines or putting the commands on the same line.
#(Get-Content "C:\Users\anon\Desktop\test.txt") -replace 'apple','apple1' -replace 'bear','bear1' |
Out-File -FilePath test1.txt
Pause
OR
#(Get-Content "C:\Users\anon\Desktop\test.txt") `
-replace 'apple','apple1' `
-replace 'bear','bear1' |
Out-File -FilePath test1.txt
Pause
Related
I have some thousands of files in a folder that I need to bulk edit their creation time to a specific order.
I have prepared a csv file with all file names and the preferred creation times, like this:
filename;filecreationTime;
file1.mp4;10/11/2022 2:50;
file2.mp4;10/11/2022 2:49;
file3.mp4;10/11/2022 2:49;
etc
I have used this suggestion to a similar previous question: https://stackoverflow.com/a/36348448/20467894 and created a code like this:
Set-Location 'path to files'
Import-Csv -Path 'path to csv file' |
ForEach-Object { (Get-Item $_.filename).CreationTime = (Get-date $_.filecreationTime) }
The outcome is this error, for each line of the csv:
Get-Item : Cannot bind argument to parameter 'Path' because it is null.
At line:2 char:32
+ ForEach-Object { (Get-Item $_.filename).CreationTime = (Get-date ...
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetItemComm
and
What am I doing wrong?
EDIT: After Theos' comment, it run once in a sample subset of my files but never run again. Now it can indeed read the filenames, but it brings a new error:
Get-date$_.filecreationTime : The term 'Get-date$_.filecreationTime' is not recognized as the name of a cmdlet, functio
n, 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:2 char:57
+ ... (Get-Item $_.filename).CreationTime = (Get-date$_.filecreationTime) }
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Get-date$_.filecreationTime:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Thanks everyone for your suggestions.
As pointed out by Theo, the problem was that in my language and regional formats the delimiter of the csv files is set to ";" instead of ",", as the latter is used as decimal...
So I had to insert an additional argument into the import csv (that was not obvious by the error expression), in order to clarify the non default delimiter:
-Delimiter ';'
So, the correct code for me was the following:
Set-Location 'path to files'
Import-Csv -Delimiter ';' -Path 'path to csv file' |
ForEach-Object { (Get-Item $_.filename).CreationTime = (Get-date $_.filecreationTime) }
Being new to PowerShell I've been following some of the guidance in these posts to write a script for what's mentioned in the subject.
Here's the script:
Get-Content -Path C:\temp\Domain.txt | Restart-Computer -force | Where-Object { $._Name -notmatch "^(SERVER01)"}
Here's the error:
Restart-Computer : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:1 char:40
+ ... et-Content -Path C:\temp\Domain.txt | Restart-Computer -force | Where ...
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:PSObject) [Restart-Computer], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.RestartComputerCommand
For reference, the DOMAIN.txt has a list of servers that will periodically change so I want to skip certain servers should they end up on the list.
The error simply means you have an empty line on your text file, you can filter the lines using .Where(..) method and exclude empty or white space lines with the help of [string]::IsNullOrWhiteSpace(..) method. I have changed -notmach for the containment operator -notin.
Note, -notin looks for an exact match within the collection $hostsToExclude.
$hostToExclude = 'server1', 'server2'
(Get-Content -Path C:\temp\Domain.txt).Where({
-not [string]::IsNullOrWhiteSpace($_) -and $_ -notin $hostToExclude
}) | Restart-Computer -Force
It's worth noting that, on your snippet, you're restarting the hosts before filtering the collection. Get-Content should be followed by Where-Object.
The desired output is to convert all of the 5 tildes into a new line character.
The command is
Powershell (Get-Content -Raw allactsconv.txt) "-replace '~~~~~', "[\r\n]" | Out-File -FilePath allactsconv.txt -Force -Encoding ascii"
It returns
At line:1 char:55
+ (Get-Content -Raw allactsconv.txt) -replace '~~~~~', [\r\n] | Out-Fil ...
+ ~
Missing type name after '['.
At line:1 char:53
+ (Get-Content -Raw allactsconv.txt) -replace '~~~~~', [\r\n] | Out-Fil ...
+ ~
Missing expression after ','.
At line:1 char:54
+ (Get-Content -Raw allactsconv.txt) -replace '~~~~~', [\r\n] | Out-Fil ...
+ ~~~~~~
Unexpected token '[\r\n]' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingTypename
I thought the problem might be the square brackets but the error is exactly the same without them.
The better solution would be to rewrite the entire batch file (it does a lot of other stuff) as a powershell script, but unfortunately I need to fix this now. At some point I will do that.
It looks like the problem is the double quotes within the double quotes, but how do I fix that? Would like to use a powershell command if I can as I need to learn it.
Based purely upon the strings you've indicated you want to replace and wish to replace them with, I'd offer the following options:
Powershell -NoProfile "(Get-Content -Raw \".\allactsconv.txt\") -Replace \"~~~~~\", \"[`r`n]\" | Out-File -FilePath \".\allactsconv.txt\" -Force -Encoding ASCII"
If you prefer to use single quotes, in PowerShell, (not my preference), then:
Powershell -NoProfile "(Get-Content -Raw '.\allactsconv.txt') -Replace '~~~~~', '[`r`n]' | Out-File -FilePath '.\allactsconv.txt' -Force -Encoding ASCII"
Working with some Windows 10 computers in my environment and looking to make a quick PowerShell script to edit a config file for our IM program.
Some quick googling to tweak my script had it working great for my test file. It's possibly not the most graceful solution, but it was working so I decided to give it the green light. Just to find out that Get-Content couldn't find my config file because it does not have an extension.
Here's my script:
(Get-Content "$env:USERPROFILE\AppData\Roaming\Config") | Foreach-Object {
$_ -replace '^autoawaytime = [0-9]+',("autoawaytime = 9")
} | Foreach-Object {
$_ -replace '^autoaxtime = [0-9]+',("autoaxtime = 99")
} | Set-Content ("$env:USERPROFILE\AppData\Roaming\Config")
And the error;
Get-Content : Cannot find path 'C:\Users\\AppData\Roaming\Config' because it
does not exist.
At C:\Users\\Desktop\textFileEdit.ps1:1 char:2
+ (Get-Content "$env:USERPROFILE\AppData\Roaming\Config" | Select BaseN ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (C:\Users\bretb\AppData\Roaming\Config:String) [Get-Content], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand
So from this I concluded that the problem is that my config file lacks a file extension and Get-Content does not like that. Could someone propose how I can Get-Content on my config file, or perhaps propose a more elegant solution for me?
In this case, it looks like path to the config file is not correct.
The common path should be something like
%userprofile%\AppData\Roaming\Company\Product\ExecutableName.Config
I'm running what I think is a relatively simple script:
$txtPath = "c:\users\xxxxxx\desktop\cgc\tx\"
$srcfiles = Get-ChildItem $txtPath -filter "*.txt*"
ForEach($txtfile in $srcfiles) {
Write-Host $txtfile
Get-Content $txtfile
}
and I get the following output:
Automatic_Post-Call_Survey_-_BC,_CC.txt
Get-Content : Cannot find path 'C:\users\x46332\desktop\cgc\Automatic_Post-Call_Survey_-_BC,_CC.txt' because it does no
t exist.
At C:\users\x46332\desktop\cgc\testcount2.ps1:34 char:13
+ Get-Content <<<< $txtfile
+ CategoryInfo : ObjectNotFound: (C:\users\x46332...ey_-_BC,_CC.txt:String) [Get-Content], ItemNotFoundEx
ception
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand
This is the output from Write-Host $txtfile followed immediately by Get-Content $txtfile and get-content seems to be the heart of my issue.
When I comment out the Get-Content line, the script generates a list of the filenames to the console. This suggests to me that the $txtPath is properly defined. However, I add Get-Content for the SAME file/same variable and for some reason, the \tx portion of the path disappears from the search string. My filename prints, but then Get-Content can't find the path for the filename is just printed.
I suspect that the "directory doesn't exist" error isn't really that the directory doesn't exist. So what should I be looking at? There's not a lot of space in my code for an error to hide, but I can't find it...thoughts?
Get-Content needs the full path e.g.:
Get-Content $txtFile.FullName
When you specify Get-Content $txtFile, PowerShell attempts to coerce the argument $txtFile to the required argument Path and to do so, it coerces the FileInfo object to a string. This process yields just the name of the file.
Another way to do this is:
$txtFile | Get-Content