Get-Content of file without Extension - powershell

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

Related

PowerShell script to set "date created" to specific times according to a csv file

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) }

How to use * in a powershell path with [

I need to copy images generated by software (HWMonitorPro). Folders and sub-folders of images cannot be modified (or I did not find how).
The images are stored in the following path:
C:\Users\hugo\Documents\DossierTest\logs\[JUN 13, 2022 - 11:06]\[LAPTOP-P15V]\[1280x960].
As you can see, a directory is created with each recording, with the date and time.
So I decided to use the following technique to be able to take the images of several captures at once:
$C = "C:\Users\hugo\Documents\DossierTest\logs"
copy-item $C'\*\`[LAPTOP-P15V`]\`[1280x960`]\789.txt' -Destination $C\test3
The line works with "[JUN 14, 2022 - 9:22]" instead of "*". This is what I get when I use the line show above:
PS C:\Windows\system32> C:\Users\hugo\Documents\DossierTest\ScriptCC.ps1
Copy-Item : Cannot retrieve the dynamic parameters for the cmdlet. The specified wildcard character pattern is not valid: [LAPTOP-P15V
At C:\Users\hugo\Documents\DossierTest\ScriptCC.ps1:3 char:1
+ copy-item $C'\*\`[LAPTOP-P15V`]\`[1280x960`]\789.txt' -Destination $C ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Copy-Item], ParameterBindingException
+ FullyQualifiedErrorId : GetDynamicParametersException,Microsoft.PowerShell.Commands.CopyItemCommand
If anyone could help me solve my problem that would be great!
PS: I'm French, sorry if it's badly written.
As it seems there's something strange with paths containing square brackets, you can use CopyTo method to copy files instead of copy-item cmdlet.
E.g. like this:
$rootfolder = "E:\tmp\logs"
$destfolder = "E:\tmp\foldertest3"
$allfiles = gci $rootfolder -File -Recurse
foreach ($file in $allfiles) {
$newfile = $file.CopyTo("$destfolder\$($file.Name)")
}
This copies all files in subdirectories to single destination folder =
you'll need to deal with t further in case there are files with same name in different subfolders.
PS: Your $C is really a terrible variable name when dealing with file paths :-)

PowerShell -replace function

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

Move-Item with -match and -LiteralPath not working

I have a file move script that looks for files with keywords in the name and moves them to a specific folder. There's about a hundred lines that all work fine, except for one of them, and the only thing I can think of is that the file has brackets in the name.
I'm already using -LiteralPath to grab the full path, but the error is weird. I've tried double quotes, double backticks, and some other options that I've found elsewhere on the boards, but nothing is working.
Here is all the relevant parts of the script (without posting the whole thing):
# Source folders
$RecipesFolder = "F:\Downloads\Downloaded Recipes\"
# Destination Folders Drive I
$CoffeeRecipes = "I:\My Recipes\Coffee Recipes\"
# Get list of files
$Files = Get-ChildItem $RecipesFolder -File -Recurse
# Process Files
foreach ($File in $Files) {
if ($File -match "Coffee") {
Move-Item -LiteralPath $RecipesFolder$File -Destination "$CoffeeRecipes" -Force
}
It's a really simple script, and every other line works fine, except that one. All the lines are written identically.
This is the full error I get (sourcepath obfuscated for security), and thank you in advance for any assistance:
Move-Item : Cannot move item because the item at 'F:\Downloads\Downloaded Recipes\[1]
Coffee Recipe - 11[1].txt' does not exist.
At Path-to-powershell-script-file:153 char:13
+ Move-Item -LiteralPath $RecipesFolder$File -Destina ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Move-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.MoveItemCommand
When I receive this error, the file disappears, and doesn't get moved to the folder, it just vanishes.

Path variable does not seem to be consistent in a single Powershell script

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