I'm trying to login to multiple servers and then get list of files from those servers.
Below is my script:
$ServerName=Get-content "D:\HOMEWARE\BLRMorningCheck\Jerry\servername.txt"
foreach ($server in $ServerName)
{
$server_host=echo $server | %{$data = $_.split(";"); Write-Output "$($data[0])"}
$Targetfolder=echo $server | %{$data = $_.split(";"); Write-Output "$($data[1])"}
$Extension =#("*.log","*.txt*")
$Files = Get-Childitem $TargetFolder -Include $Extension -Recurse
echo $Files
}
When I run I debug mode I see that it really doesnt pick the files.
Error:
Get-ChildItem : Illegal characters in path.
At D:\HOMEWARE\BLRMorningCheck\Jerry\test.ps1:14 char:23
+ $Files = Get-Childitem <<<< $TargetFolder -Include $Extension -Recurse
+ CategoryInfo : InvalidArgument: (D:\HOMEWARE\BLR...ck\Jerry\Check":String) [Get-ChildItem], ArgumentException
+ FullyQualifiedErrorId : ItemExistsArgumentError,Microsoft.PowerShell.Commands.GetChildItemCommand
Get-ChildItem : Cannot find path 'D:\HOMEWARE\BLRMorningCheck\Jerry\"\srvparrtfh01\d$\HOMEWARE\BLRMorningCheck\Jerry\Check"' because it does not exist.
At D:\HOMEWARE\BLRMorningCheck\Jerry\test.ps1:14 char:23
+ $Files = Get-Childitem <<<< $TargetFolder -Include $Extension -Recurse
+ CategoryInfo : ObjectNotFound: (D:\HOMEWARE\BLR...ck\Jerry\Check":String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
Note: If I run it manually, example
$Files = Get-Childitem \\servername\d$\HOMEWARE\BLRMorningCheck\Jerry\Check -Include "*.log","*.txt*" -Recurse
I get the output.
As #arco444 and #PetSerAl mentioned in the comments: your path string has leading/trailing double quotes, which are invalid characters in a path. You need to remove them to make the path work as intended:
$Files = Get-Childitem ($TargetFolder -replace '^"|"$') -Include $Extension -Recurse
Of course, since your input file seems to be a some sort of CSV, you could use Import-Csv instead of reading the file with Get-Content and manually splitting the fields. That would already take care of the double quotes on file import.
$filename = 'D:\HOMEWARE\BLRMorningCheck\Jerry\servername.txt'
$extension = '*.log', '*.txt*'
Import-Csv $filename -Delimiter ';' -Header 'ComputerName', 'TargetFolder' | % {
Get-Childitem $_.TargetFolder -Include $extension -Recurse
}
This was an absolute nightmare, get-childitem cannot except a string variable if there are multiple paths.
Get-ChildItem -Path "\server1\c$\temp", "\server1\d$\temp" -File
-recurse # works
$path = '"\server1\c$\temp", "\server1\d$\temp"'; Get-ChildItem -Path "\server1\c$\temp", "\server1\d$\temp" -File
-recurse # fails with cannot find path
$path = "'"\server1\c$\temp", "\server1\d$\temp'""; Get-ChildItem -Path "\server1\c$\temp", "\server1\d$\temp" -File
-recurse # fails with illegal character message (the tick)
Any string that has multiple paths fails, however an array with += as shown below will work.
$servers = #("server1", "server2");
$partialPaths = #("\c$\temp\", "\d$\temp\");
foreach ($server in $servers)
{
$paths = #();
foreach ($partialPath in $partialPaths)
{
$paths += "\\" + $server + $partialPath;
}
}
Get-ChildItem -Path $paths -File -recurse;
Related
The Script:
Creates a list of folders based on the filenames in the scripts root directory, each folder breaks down the name by "Year/Month/Day"
Moves each file to the designated folder
Error Message:
CategoryInfo : ObjectNotFound:
(S:\Data\TECHNOL...59_20180108.txt:String)
[Move-Item], ItemNotFoundException FullyQualifiedErrorId :
PathNotFound,Microsoft.PowerShell.Commands.MoveItemCommand
My Issue
The files will not move to the correct endpath
#Create Directory
Set-StrictMode -Version 2
$rootPath = split-path -parent $MyInvocation.MyCommand.Definition
cd $rootPath
$FileNameArray = Get-ChildItem -Filter "*.txt"
$FileNameArray = $FileNameArray -replace "....$"
$FileNameArray = $FileNameArray -replace "^59_"
Foreach($f in $FileNameArray)
{
$Year = $f -replace "^\d{0}|\d{4}$" #"....$"
$Month = $f -replace "^\d{4}|\d{2}$"
$Month = $Month | sort -Unique
$Day = $f -replace "^\d{6}|\d{0}$"
#Loop 2a
Foreach($m1 in $Month){
#Loop 2a-a
Foreach($d1 in $Day){
Move-Item -Path ($rootPath + '\59_' + $file + '.txt')
-Destination ($rootPath + '\' + $Year + '\' + $m1 + '\' + $d1)
}
}
}
Apologies for the spaghetti code & simple question, I am new to both Computer Science and PowerShell.
The following script has two security features:
The MD command has a trailing -confirm you have to answer
The Move-Item has a -WhatIf which shows what would be done without the Parameter
If the script works OK, remove them both.
## Q:\Test\2018\05\03\SO_50158185.ps1
Set-StrictMode -Version 2
$rootPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
cd $rootPath
Get-ChildItem "59_20[0-9][0-9][0-1][0-9][0-3][0-9].txt" |
Where-Object {$_.BaseName -Match '59_(?<year>\d{4})(?<Month>\d{2})(?<Day>\d{2})'}|
ForEach-Object {
$DestDir = Join-Path $rootPath ("{0}\{1}\{2}" -f $Matches.Year,$Matches.Month,$Matches.Day)
If (!(Test-Path $DestDir)) {MD $DestDir -Confirm| Out-Null}
$_ | Move-Item -Destination $DestDir -WhatIf
}
Figured it out guys! Just needed to change $file to $f. Thanks for all the help.
I am trying to search a directory structure, and files for all instances of where a pattern exists. Than I want that file location recorded in a log file that I can review latter. I looked at various posts, but I have not found a similar example where this is happening. Reviewed posts include:
PowerShell Scripting - Get-ChildItem
Search List for unique pattern
Search directory and sub-directories for pattern in a file
Use an Easy PowerShell Command to Search Files for Information
Get full path of the files in PowerShell
Here is the code I am using to recuse through the folder structure:
#Set variables for paths
$Results = "C:\Results"
$Source = "C:\Test\*"
$Destination = "C:\MyTest\"
#Create file name for each report with date and time of run
$ReportDate = (Get-Date).ToString("dd-MM-yyyy-hh-mm-ss")
$CustomPattern = Read-Host 'What pattern are you looing for?'
$CustomPatternLog = New-Item -itemType File -Path C:\Results -Name $("CustomerPattern_" + $ReportDate + ".txt")
$CustomPattern = foreach ($file in Get-ChildItem -Path $Destination -Recurse | Select-String -pattern $CustomPattern | Select-Object -Unique Path) {$file.path}
$CustomPattern > "$($Results)\$($CustomPatternLog)"
However, this code is returning the following error:
Get-ChildItem : The specified path, file name, or both are too long.
The fully qualified file name must be less than 260 characters, and
the directory name must be less than 248 characters. At line:19
char:36
+ $CustomPattern = foreach ($file in Get-ChildItem -Path $Destination -Recurse | S ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ReadError: (C:\Test\Mor...ofiles\Customer:St ring) [Get-ChildItem],
PathTooLongException
+ FullyQualifiedErrorId : DirIOError,Microsoft.PowerShell.Commands.GetChil dItemCommand
Do you have a better way to do the same operation?
replace this
$CustomPatternLog = New-Item -itemType File -Path C:\Results -Name $("CustomerPattern_" + $ReportDate + ".txt")
$CustomPattern = foreach ($file in Get-ChildItem -Path $Destination -Recurse | Select-String -pattern $CustomPattern | Select-Object -Unique Path) {$file.path}
$CustomPattern > "$($Results)\$($CustomPatternLog)"
with this
$files = Get-ChildItem -Path $Destination -Recurse
#in case you would need the path replace FullName with PsParentPath
$result = ($files | ?{$_.name -like "*$CustomPattern*"}).FullName
$result | out-file ($CustomPattern + "_" + $ReportDate + ".txt")
and since its shell you can do the same with one liner
(Get-ChildItem -Path $Destination -Recurse | ?{$_.name -like "*$CustomPattern*"}).FullName | out-file ($CustomPattern + "_" + $ReportDate + ".txt")
I'm having problems after a folder is copied to a different location, I need to rename the folders in the directory to remove ".deploy" from the end, but I get the following error below. I have Googled around for PowerShell admin permissions, but cannot seem to find a 'catch-all' for my scenario.
Get-Content : Access to the path 'C:\OldUserBackup\a.deploy' is denied.
At C:\PSScripts\DesktopSwap\TestMergeDir.ps1:28 char:14
+ (Get-Content $file.PSPath) |
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (C:\OldUserBackup\a.deploy:String) [Get-Content], UnauthorizedAccessException
+ FullyQualifiedErrorId : GetContentReaderUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetContentCommand
Here is what I have:
$UserName = [Environment]::UserName
$CurrUser = [Environment]::UserName + '.deploy'
$OldUserDir = 'C:\OldUserBackup'
$CurrDate = Get-Date -format G
$PathExist = Test-Path $OldUserDir
if ($PathExist -eq $true) {
#Copy Desktop, Downloads, Favorites, Documents, Music, Pictures, Videos
Copy-Item -Path $OldUserDir -Destination C:\Users\$UserName\Desktop\CopyTest -Recurse -Force
$configFiles = Get-ChildItem $OldUserDir *.deploy -rec
foreach ($file in $configFiles) {
(Get-Content $file.PSPath) |
Foreach-Object { $_ -replace ".deploy", "" } |
Set-Content $file.PSPath
}
}
You should use the -Directory switch on the Get-ChildItem cmdlet to only get directories. Then use the Rename-Item cmdlet to rename the folders. I use the -replace function with a simple regex to get the new folder name:
$deployFolders = Get-ChildItem $OldUserDir *.deploy -rec -Directory
$deployFolders | Foreach {
$_ | Rename-Item -NewName ($_.Name -replace ('\.deploy$') )
}
You don't even have to use the Foreach-Object cmdlet (Thanks to AnsgarWiechers):
Get-ChildItem $OldUserDir *.deploy -rec -Directory |
Rename-Item -NewName { $_.Name -replace ('\.deploy$') }
I want to remove bak files after zip from all subfolder for given path, so all duplicate files with extension .bak will be removed,i run below script but getting error.
$filePath = "d:\Test\"
$Afiles = Get-ChildItem -Recurse -Path $filePath | Where-Object {$_.Extension -eq ".bak"}
$Bfiles = Get-ChildItem -Recurse -Path $filePath | Where-Object {$_.Extension -eq ".7z"}
$Alist = #()
$Blist = #()
foreach( $A in $Afiles) {
$Alist += $A.baseName
}
foreach( $B in $Bfiles) {
$Blist += $B.baseName
}
foreach($A in $Alist) {
if($Blist -contains $a)
{
rm ("$A.bak")
}
}
I am receiving below error :
Remove-Item : Cannot find path 'C:\Users\******\Desktop\master_backup_2015_08_21_013722_8370267.bak' because it does not exist.
At C:\Users\*****\Desktop\duplicatedelete1.ps1:26 char:10
+ rm <<<< ("$A.bak")
+ CategoryInfo : ObjectNotFound: (C:\Users\****....722_8370267.bak:String) [Remove-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand
You're receiving error because you're not specifying full path for rm command and PowerShell tries to delete file in your current directory.
Try this:
$Path = 'D:\Test'
Get-ChildItem -Path $Path -Recurse -Filter '*.7z' | ForEach-Object {
$BackupFile = Join-Path -Path (Split-Path $_.FullName -Parent) -ChildPath ($_.BaseName + '.bak')
if(Test-Path -Path $BackupFile){
Remove-Item -Path $BackupFile
}
}
Using PowerShell 4.0,
I am trying to get the size of multiple directories and I am getting very inconsistent results between what windows tells me and what my code is telling me.
The code in question is:
$temp4 = ($folderInfo.rootFolder).fullname
$folderInfo.directories += Get-ChildItem -LiteralPath $temp4 -Recurse -Force -Directory
$folderInfo.directories += $folderInfo.rootFolder
foreach ($dir in $folderInfo.directories)
{
$temp3 = $dir.fullname
$temp2 = Get-ChildItem -LiteralPath $temp3 -Force
$temp = (Get-ChildItem -LiteralPath $dir.fullname -Force -File | Measure-Object -Property length -Sum -ErrorAction SilentlyContinue).Sum
$folderInfo.totalSize += $temp
}
return $folderInfo
if $folderInfo.rootFolder = D:\sample
then I get what I want
but if $folderInfo.rootFolder = D:\[sample
then I get
Get-ChildItem : Cannot retrieve the dynamic parameters for the cmdlet. The specified wildcard character pattern is not valid: sample [sample
At C:\powershell scripts\test.ps1:55 char:12
+ $temp = (Get-ChildItem $dir.fullname -Force -File | Measure-Object -Property l ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Get-ChildItem], ParameterBindingException
+ FullyQualifiedErrorId : GetDynamicParametersException,Microsoft.PowerShell.Commands.GetChildItemCommand
The same holds true if D:\sample contains a folder somewhere in it's children that is "[sample". I will get correct results from everything else, but anything in or beyond the problem directory. Both $dir.pspath and $dir.fullname screw things up.
Edit: changed the above code to reflect it's current state and included the full error.
edit again: The code above now has some debugging temp variables.
Use the -LiteralPath parameter in place of -Path to suppress the wildcard globbing. Also, since you're using V4, you can use the -Directory switch and dispense with the $_.iscontainer filter:
$folderInfo.directories =
Get-ChildItem -LiteralPath $folderInfo.rootFolder -Recurse -Force -Directory
If you have more squre brackets farther down the directory tree, keep using literpath in subsequent Get-ChildItem commands:
$folderInfo.directories += Get-ChildItem -LiteralPath $folderInfo.rootFolder -Recurse -Force -Directory
$folderInfo.directories += Get-Item -LiteralPath $folderInfo.rootFolder
foreach ($dir in $folderInfo.directories)
{
$temp2 = Get-ChildItem -LiteralPath $dir.PSPath -Force
$temp = (Get-ChildItem -LiteralPath $dir.fullname -Force -File | Measure-Object -Property length -Sum -ErrorAction SilentlyContinue).Sum
$folderInfo.totalSize += $temp
}
return $folderInfo