Trying to use PowerShell to remove an odd character, but it keeps breaking on [:
Filename is test [t].txt
Dir | Rename-Item -NewName { $_.Name -replace "[","_" }
Results in:
PS D:\test> Dir | Rename-Item -NewName { $_.Name -replace "[","_" }
Rename-Item : The input to the script block for parameter 'NewName' failed.
Invalid regular expression pattern: [.
At line:1 char:27
+ Dir | Rename-Item -NewName <<<< { $_.Name -replace "[","_" }
+ CategoryInfo : InvalidArgument: (test [t].txt:PSObject) [Rename-Item], ParameterBindingException
+ FullyQualifiedErrorId : ScriptBlockArgumentInvocationFailed,Microsoft.PowerShell.Commands.RenameItemCommand
I've tried a few common ways to escape the character \[, '[', ... and nada.
Thoughts and ideas?
PS: Trying the Replace() method with \[ escape:
PS D:\test> Dir | Rename-Item -NewName{ $_.Name.Replace("\[","_")}
Rename-Item : Cannot rename because item at 'Microsoft.PowerShell.Core\
FileSystem::D:\test\test [t].txt' does not exist.
At line:1 char:18
+ Dir | Rename-Item <<<< -NewName{ $_.Name.Replace("\[","_")}
+ CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
PPS: The file DOES exist:
PS D:\test> dir
Directory: D:\test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 1/27/2018 4:08 PM 448 rb.bat
-a--- 1/27/2018 3:04 PM 4 test [t].txt
The appending of the PS header to the path by something inside PS when it sees a [ in the file name is the problem. If I replace the [ (bracket) with a ( (paren) everything works as expected.
The escape charachter is a backslash. So your regex pattern should look like this:
Get-ChildItem |
Rename-Item -NewName {$_.Name -replace '\[|\]','_'}
This will replace the opening square bracket and the closing square bracket.
Yes, I see that you resolved your situation with brute force. This code appears to produce the filename you desire.
PS C:\src\t\renfunc> Get-ChildItem
Directory: C:\src\t\renfunc
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2018-09-11 08:51 7 test [2].txt
PS C:\src\t\renfunc> Get-ChildItem | ForEach-Object { $_.Name -replace '\[|\]','_' }
test _2_.txt
Related
I'm trying to run a powershell command to extract all zip files into a folder to a new path.
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command Get-ChildItem 'Z:\audio\music\purchased-music\incoming' -Filter *.zip | Expand-Archive -DestinationPath 'Z:\audio\music\purchased-music\incoming-unzipped' -Force
It looks like the command should work, but I get an error as such:
Expand-Archive : Cannot validate argument on parameter 'Path'. 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:140
+ ... ter *.zip | Expand-Archive -DestinationPath 'Z:\audio\music\purchased ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:PSObject) [Expand-Archive], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Expand-Archive
Expand-Archive : Cannot validate argument on parameter 'Path'. 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:140
+ ... ter *.zip | Expand-Archive -DestinationPath 'Z:\audio\music\purchased ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:PSObject) [Expand-Archive], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Expand-Archive
Expand-Archive : The path ' Directory: Z:\audio\music\purchased-music\incoming' either does not exist or is not a valid file system path.
At line:1 char:140
+ ... ter *.zip | Expand-Archive -DestinationPath 'Z:\audio\music\purchased ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: ( Directory: ...-music\incoming:String) [Expand-Archive], InvalidOperationException
+ FullyQualifiedErrorId : ArchiveCmdletPathNotFound,Expand-Archive
The path and destination both do exist:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command Get-ChildItem 'Z:\audio\music\purchased-music\incoming' -Filter *.zip
Directory: Z:\audio\music\purchased-music\incoming
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2/6/2021 4:28 PM 38489484 Satsuma.zip
PS C:\Windows\System32\WindowsPowerShell\v1.0> dir Z:\audio\music\purchased-music\incoming-unzipped
Directory: Z:\audio\music\purchased-music\incoming-unzipped
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 12/16/2020 2:15 AM 20320 touch.txt
To expand on Olaf's helpful comment, this would work with braces as per powershell /?, or about_PowerShell_exe documentation:
PS C:\Windows\System32\WindowsPowerShell\v1.0> C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command {Get-ChildItem 'Z:\audio\music\purchased-music\incoming' -Filter *.zip | Expand-Archive -DestinationPath 'Z:\audio\music\purchased-music\incoming-unzipped' -Force}
Since you're using PowerShell, you don't need to launch the exe to execute a command:
Get-ChildItem 'Z:\audio\music\purchased-music\incoming' -Filter *.zip |
Expand-Archive -DestinationPath 'Z:\audio\music\purchased-music\incoming-unzipped' -Force
(the PS C:\Windows\System32\WindowsPowerShell\v1.0> isn't relevant to code execution as you're specifying full paths Z:\audio\... etc - you could be running this from any location)
I'm currently working on a script to import 2 csv files, compare the fqdn columns and output the results to a file.
The issue is after many hours of testing I'm at the point that it looks like my script is working up until the point of getting the path for each file that needs to be imported but I can't seem to get the import-csv command to do what I need it to.
I'd appreciate any guidance you can provide.
My script so far and the error I'm getting are below:
$CMDB_Installed = Get-ChildItem -Path C:\Users\nha1\Desktop\Reports\CMDBInstall | Sort CreationTime -Descending | Select -expa FullName -First 1 | Out-String
$SCOM_AgentList = Get-ChildItem -Path C:\Users\nha1\Desktop\Reports\SCOMUAT | Sort CreationTime -Descending | Select -expa FullName -First 1 | Out-String
$SL = Import-Csv $SCOM_AgentList
$CL = Import-Csv $CMDB_Installed
Compare-Object -ReferenceObject $CL -DifferenceObject $SL -Property fqdn |
Export-Csv -NoTypeInformation -Path = C:\Users\nha1\Desktop\Reports\AuditOutput\UATNeedsAgent+SCOM\UATHosts-NotinSCOM$(get-date -format yyyy-MM-dd).csv
Error Message:
import-csv : Illegal characters in path.
At line:4 char:7
+ $SL = import-csv $SCOM_AgentList
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (:) [Import-Csv], ArgumentException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.ImportCsvCommand
import-csv : Illegal characters in path.
At line:5 char:7
+ $CL = import-csv $CMDB_Installed
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (:) [Import-Csv], ArgumentException
+ FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.ImportCsvCommand
$CMDB_Installed = ... | Select -expa FullName -First 1 | Out-String
Don't use Out-String, unless you want a for-display, multi-line string representation.
Your file-path variables therefore contain newlines (line breaks), which Import-Csv complains about, given that newlines in file names are illegal in NTFS (on Windows).
Simply omit the Out-String call, given that Select -expa FullName -First 1 by definition already outputs a string (given that the .FullName property on the objects output by Get-ChildItem is [string]-typed).
To recreate the problem:
PS> Import-Csv "foo`n" # illegal line break in file path
Import-Csv : Illegal characters in path.
To demonstrate that Out-String produces a multi-line string even with a single-line string as input:
PS> ('foo' | Out-String).EndsWith("`n")
True
I am attempting to run a powershell script from my PC against a txt file that contains numerous remote PC's. I want to run a script against that list of PC's that will search a certain file path for specific file name and/or file extension.
I have been attempting to do a for each loop with my txt file inserted as a variable. I am also attempting to get the file names returned to me via the cmdlet "Get-ChildItem."
I have not been able to get anything to work correctly so far. Can anyone point me in the right direction with this? Below are a couple of things I have tried so far...
**
PS C:\Windows\system32> $name= gc env:computername
$computers= get-content -path c:\users\person\Desktop\book2.txt
$csvfile = "c:\temp\$name.csv"
foreach ($computer in $computers) {Get-ChildItem -recurse -filter "C:\Users\*.locky"}
export-csv -filepath $csvfile
**
*
Get-ChildItem : Second path fragment must not be a drive or UNC name.
Parameter name: path2
At line:4 char:36
+ foreach ($computer in $computers) {Get-ChildItem -recurse -filter "C:\Users\*.lo ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (C:\Windows\system32:String) [Get-ChildItem], Argume
ntException
+ FullyQualifiedErrorId : DirArgumentError,Microsoft.PowerShell.Commands.GetChildItemCommand
Export-Csv : A parameter cannot be found that matches parameter name 'filepath'.
At line:5 char:12
+ export-csv -filepath $csvfile
+ ~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Export-Csv], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.ExportCsvCommand
*
AND
C:\Windows\system32> ForEach ($system in (Get-Content C:\temp\Book2.txt))
if ($exists in (Test-Path \\$system\c$\Users\*.locky))
{
Get-Command $exists | fl Path,FileVersion | Out-File c:\temp\results.csv -Append
}
At line:1 char:53
+ ForEach ($system in (Get-Content C:\temp\Book2.txt))
+ ~
Missing statement body in foreach loop.
At line:3 char:14
+ if ($exists in (Test-Path \\$system\c$\Users\*.locky))
+ ~~
Unexpected token 'in' in expression or statement.
At line:3 char:14
+ if ($exists in (Test-Path \\$system\c$\Users\*.locky))
+ ~~
Missing closing ')' after expression in 'if' statement.
At line:3 char:55
+ if ($exists in (Test-Path \\$system\c$\Users\*.locky))
+ ~
Unexpected token ')' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingForeachStatement
Wrong -filter parameter in Get-ChildItem cmdlet. Next code snippet should work:
foreach ($computer in $computers) {"\\$computer\C$\Users"|`
Get-ChildItem -recurse -filter "*.locky"}
Get-ChildItem -Name *.txt | Rename-Item -NewName { $_.name -replace '\.txt','.log' }
I have 3 text files in my current path, I'm using this snip bit of code found in the last example of...
get-help rename-item -full
(Powershell Version 2.0). For whatever reason, I keep receiving the following error:
Rename-Item : Cannot bind argument to parameter 'NewName' because it is an empty string.
At line:1 char:40
+ Get-ChildItem -Name *.txt | Rename-Item <<<< -NewName { $_.name -replace
'\.txt','.log' }
+ CategoryInfo : InvalidData: (testfile3.txt:PSObject) [Rename-Item],
ParameterBindingValidationException
+ FullyQualifiedErrorId :
ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.Rena
meItemCommand
Clearly my alteration form .txt to .log isn't an empty string, and this matches exactly the same code as in found in Microsoft's last example of the cmdlet rename-item.
Either don't use the -Name parameter since that outputs just strings containing the full path or don't reference the Name property:
Get-ChildItem -Name *.txt | Rename-Item -NewName { $_ -replace '\.txt','.log' }
If you have a filename such as "Committee minutes [October 2010] - hq.doc", how do you get Powershell to replace the square brackets? The following doesn't work:
ls -filter *`[*`]* | foreach -Process { Rename-Item $_ -NewName ($_.Name -replace '\[', '\(') | Rename-Item $_ -NewName ($_.Name -replace '\]', '\)')}
I get the error:
Rename-Item : Cannot rename because item at 'Committee minutes [October 2010] - hq.doc' does not exist.
At line:1 char:53
+ ls -filter *`[*`]* | foreach -Process { Rename-Item <<<< $_ -NewName ($_.Name -replace '\['
]', '\)')}
+ CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
Unfortunately this is a known bug/limitation of PowerShell. A suitable and actually not bad workaround is to use Move-Item for renaming items: it has the -LiteralPath parameter which is missing in Rename-Item.
See reported issues:
https://connect.microsoft.com/PowerShell/feedback/details/277707/rename-item-fails-when-renaming-a-file-and-the-filename-contains-brackets
https://connect.microsoft.com/PowerShell/feedback/details/553052/rename-item-literalpath