I am trying to delete bunch of files based on a csv file. Files listed in the csv file should be deleted from the target file share. When I run the script I am in the target folder but I am getting the following error:
Remove-Item : The input object cannot be bound to any parameters for the command either because the command does not take pipeline input or the input and its properties
do not match any of the parameters that take pipeline input.
At line:9 char:56
+ Get-Childitem | where {$_.Name -match $filename} | Remove-Item -verbose -$fi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (gp.html:PSObject) [Remove-Item], ParameterBindingException
+ FullyQualifiedErrorId : InputObjectNotBound,Microsoft.PowerShell.Commands.RemoveItemCommand
Code below:
$csvFile = Import-csv "C:\\DeleteFiles.csv"
foreach($user in $csvFile)
{
$filename = $user.FileName
write-host $filename
Get-Childitem | where {$_.Name -match $filename} | Remove-Item -verbose -$fileName
}
According to your comment, you have some empty filenames in the csv file. This solution should be more robust:
$csvFile = Import-csv "C:\\DeleteFiles.csv"
foreach($user in $csvFile)
{
$filename = $user.FileName
write-host "The filename is '$filename'"
if (test-path $filename)
{
Remove-Item -verbose $fileName
}
else
{
Write-Host "File '$filename' not found"
}
}
Related
I have to move files from a folder corresponding to a CSV column like that :
id
name
1a
file1
2b
file2
3c
file3
4d
file4
So if in my folder I have a file named file1 I need to create a folder named 1a and put file1 inside.
I have the following script
$CsvId = Import-Csv './test.csv'
$sourcePath= "C:\Users\olong\Desktop\object"
$dirPath = "C:\Users\olong\Desktop\dir"
$files = Get-ChildItem -Path $sourcePath | ForEach-Object -Process {[System.IO.Path]::GetFileNameWithoutExtension($_)}
$pattern = '(?<=_).*(?=_)'
ForEach ($item In $CsvId) {
$objectID = $item.'id'
$docID = $item.'name'
$location = $dirPath+ "\" + $objectID
Foreach ($file in $files) {
if($file -contains $docID) {
if (-not (Test-Path -Path $location)) {
mkdir -Path $location
}
Move-Item ($file.FullName) -Destination $location -Verbose -Force
}
}
}
But it gives me that error :
Move-Item : Cannot bind argument to parameter 'Path' because it is null.
At C:\Users\olong\Desktop\scriptMove.ps1:19 char:15
+ Move-Item ($file.FullName) -Destination $location -Verbose -Force
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Move-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.MoveItemCommand
With PowerShell's debugger $file is not null and with or without parenthesis on $file.FullName does nothing
I think what you want to do is to get the file(s) as mentioned in the csv under header 'name' having any extension into a subfolder as mentioned in field 'id' and create that subfolder first if it does not already exist.
If my assumtion is correct, you can try below:
$sourcePath = "C:\Users\olong\Desktop\object"
$destinationPath = "C:\Users\olong\Desktop\dir"
Import-Csv -Path './test.csv' | ForEach-Object {
$targetDirectory = Join-Path -Path $destinationPath -ChildPath $_.id
# create the output subfolder if it does not already exist
$null = New-Item -Path $targetDirectory -ItemType Directory -Force
# next use the file basename from the $_.name column as filter and move the file(s)
Get-ChildItem -Path $sourcePath -Filter "$($_.name).*" -File | Move-Item -Destination $targetDirectory
}
I receive the error message "Illegal Characters in path" when running the following simple script that utilizes the Copy-Item command:
$Files = Get-Content output.txt
ForEach($File in $Files){
echo $File
$Directory = Split-Path -Parent $File
$newDirectory = ($Directory | Out-String) -replace "C:\\test", "C:\Backup"
echo $newDirectory
Copy-Item $File $newDirectory -force -recurse
}
As you can see the $Files variable is pulling each line into an array. Each line is actually a file path and name. The echo outputs look fine and are below:
C:\test\testing\text.txt
C:\Backup\testing
The first is the orginal file location that is to be copied, the second is the folder to copy it into. Can anyone help me figure out what the "Illegal character" is in these two paths. The error points to the source path.
Full Error Code is below:
Copy-Item : Illegal characters in path.
At C:\users\lane.pulcini\desktop\searchfiles\testcopy.ps1:7 char:10
+ Copy-Item <<<< $File $newDirectory -force -recurse
+ CategoryInfo : NotSpecified: (:) [Copy-Item], ArgumentException
+ FullyQualifiedErrorId : S System.ArgumentException,Microsoft.PowerShell.Commands.CopyItemCommand
Out-String is putting something on the end of the string, so you need to trim it:
$newDirectory = (($Directory | Out-String) -replace "C:\\test", "C:\Backup").TrimEnd()
...or, remove Out-String--I'm not sure why you have it there:
$newDirectory = $Directory -replace "C:\\test", "C:\Backup"
You can see this by checking the length property:
PS C:\> $d = $Directory | out-string
PS C:\> $d.Length
17
PS C:\> $Directory.Length
15
If you want the script to create the subfolder under C:\Backup if it doesn't exist, place the following before the Copy-Item line:
if(!(test-path $newDirectory)){
New-Item $newDirectory -type directory
}
I have a script that I am trying to get to sort through a directory and open all the zip files and store the text files all to one directory. Here is the code:
#Script to open zip files in tree
New-Item E:\Files -type directory
Get-ChildItem -Path E:\SNL_Insurance\* -Recurse -Exclude "*.md5"|
ForEach-Object {
$file = $_
write-host $file;
$destination = "E:\Files"
$shell = New-Object -com shell.application
$zip = $shell.NameSpace($file) |
foreach($item in $_.items()){
$shell.Namespace($destination).copyhere($item)
}
}
I think I almost have it, but keep getting this error (any elaboration on piping would be helpful):
Unexpected token 'in' in expression or statement.
At E:\Expand-ZIPFile.ps1:14 char:19
+ foreach($item in <<<< $_.items()){
+ CategoryInfo : ParserError: (in:String) [], ParseException
+ FullyQualifiedErrorId : UnexpectedToken
EDIT:
Ahh... thanks for that distinction. I made your edits but after each of my "write-host" checks to see the file name I get the following error:
`You cannot call a method on a null-valued expression. At E:\Expand-ZIPFile.ps1:14 char:30 + foreach($item in $zip.items <<<< ()){ + CategoryInfo : InvalidOperation: (items:String) [], RuntimeException + FullyQualifiedErrorId : InvokeMethodOnNull
EDIT2: So the original code does copy files to a new directory but also copies the whole zip file over. I tried to add an if statement to only copy files that are .txt but the code just steps through each directory without copying anything. If you have any idea that would be appreciated as I have exhausted all my ideas. Here is the code:
new-Item E:\Files -type directory
Get-Childitem -path E:\SNL_Insurance\* -recurse -exclude "*.md5" |
Foreach-object {
$file = $_
write-host $file;
$destination = "E:\Files"
$shell = new-object -com shell.application
$zip = $shell.NameSpace($file.Fullname)
foreach($item in $zip.items()){
if ($item.Extension -eq ".txt") {
$shell.Namespace($destination).copyhere($item)
}
}
}
You're confusing foreach with ForEach-Object loops. The former neither read from nor do they write to pipelines. Also, $file is a FileInfo object, not a path. The NameSpace method expects a path string, so you need to use $file.FullName.
Replace
$zip = $shell.NameSpace($file) |
foreach($item in $_.items()){
$shell.Namespace($destination).copyhere($item)
}
with
$zip = $shell.NameSpace($file.FullName)
foreach($item in $zip.items()){
$shell.Namespace($destination).copyhere($item)
}
I am very new to powershell and situation is that I have some unneeded users folder that must be deleted on different servers. Path on all servers is f.e. "\server1\hiddenshare$\username" My CSV looks like:
ServerName,FolderName
SERVER1,AAAA
SERVER2,AAA1
SERVER3,AAA2
And I am trying to run this code:
$path = "C:\temp\servers_folders.csv"
$ServerName = Import-Csv -Path $path
$FolderName = Import-CSV -Path $path
Import-Csv -Path $path | % {
Remove-Item -Path \\$ServerName\hiddenshare$\$FolderName -Recurse
}
After all I get this error:
Remove-Item : Cannot find path '\\ \$\ ' because it does not exist.
At C:\temp\servers_folders.csv.ps1:5 char:3
+ Remove-Item -Path \\$ServerName\hiddenshare$\$FolderName -Recurse
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (\\ \usr$\ :String) [Remove-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand
you dont need to import your csv more than once.
Inside the foreach block you have to reference the current item by $_
try this, remove -whatif if it's ok
$servers=import-csv .\servers.csv
$servers | %{
remove-item -path \\$($_.servername)\users$\$($_.FolderName) -whatif
}
I have been working on a PowerShell script for the better part of well a week or two. I've been able to get some parts of it working however I'm unable to fully get this automated.
I deal with a lot of CSV files on a daily basis, I have been tasked with uploading them into our software however sometimes they're too large to handle so I break them down based upon their "type" (it's a column in the CSV) and I export it to a single CSV per "type". I've been able to accomplish this with the following:
$file = gci -Filter "*.csv";
Import-Csv $file `
| Group-Object –Property “type” `
| Foreach-Object `
{
$path=$_.name+”.csv” ; $_.group `
| Export-Csv –Path $path –NoTypeInformation
}
So this works wonderfully, for each individual CSV. Unfortunately I don't have the time to do this for each individual CSV. Now I come to my other PowerShell script:
get-childitem -Filter "*.csv" `
| select-object basename `
| foreach-object{ $path=$_.basename+".csv" #iterate through files.
if(!(Test-Path -path $_.basename)) #If the folder of the file can't be found then it will attempt to create it.
{
New-Item $_.basename -type directory; $file=$_.basename+".csv";
Import-Csv $file `
| Group-Object -Property "Type" `
| Foreach-Object {
$path=$_.name+".csv"; $_.group `
| `
if(!(Test-Path -path $path2))
{
New-Item $path2 -type directory
Export-Csv -Path $path2 + "\" + $path -NoTypeInformation
}
else
{
"Failed on: " + $_.basename
#Export-Csv -Path $_.basename + "\" + $path -NoTypeInformation
}
}
}
else
{
Import-Csv $path `
| Group-Object -Property "Type" `
| Foreach-Object {$path=$_.basename+".csv" ; $_.group
if(Test-Path -path $._)
{
New-Item $path2 -type directory
Export-Csv -Path $path2 + "\" + $path -NoTypeInformation
}
#else
#{
Write-Host "Failed on: $_.basename"
#Export-Csv -Path $_.basename + "\" + $path -NoTypeInformation
#}
}
}
}
I just can't wrap my head around "why" this isn't working effectively. I have two conditionals. Is there a folder for the CSV? If no create one. I have to have another one because one of the "types" contains a \ which errors out if I don't have the folder, so I automatically try to create it. When I run the script I get the Path is null.
The Error is:
The term ' ' 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\c.burkinshaw\foldermake.ps1:11 char:26
+ | ` <<<<
+ CategoryInfo : ObjectNotFound: ( :String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Test-Path : Cannot bind argument to parameter 'Path' because it is null.
At C:\Users\c.burkinshaw\foldermake.ps1:12 char:45
+ if(!(Test-Path -path <<<< $path2))
+ CategoryInfo : InvalidData: (:) [Test-Path], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.TestPathCommand
Any help would be greatly appreciated, if you have questions please don't hesitate to ask.
You have not defined $path2 anywhere, so something like test-path -path $path2 will say path is null. And in one place you are using $._ which will again give errors.
Edit after question updated with error message:
Your error message also says the same
Test-Path : Cannot bind argument to parameter 'Path' because it is
null. At C:\Users\c.burkinshaw\foldermake.ps1:12 char:45
+ if(!(Test-Path -path <<<< $path2))
Also the other error is in:
$path=$_.name+".csv"; $_.group `
| `
what are you trying to do here with the $_.group?
It is not proper. You cannot do $_.group | and provide some if statement.
Other comments:
Why are using $_.basename and then appending .csv? You could have just used $_.name. Try to not use the select-object basename - I don't see the value.
Extract the common import-csv and export-csv part into a function.