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"}
Related
This powershell snippet should display size and name of the files in directory on shared drive,
working fine with one path raising error with other path
copied two logs which raise error(log2) and other worked fine(log1)
for long path issue i tried like $joined_path2=Join-Path -LiteralPath '\\?\UNC\' -ChildPath $joined_path
$check_dir_path=\\XXXXXX.yy.NN.com\qeshare\Environments #(not working)
#check_dir_path=\\XXXXXX.yy.NN.com\qeshare\Environments\Private\ccccc #(working fine with this path)
$folders_in_dir=Get-ChildItem $check_dir_path -directory | Foreach-Object {$_.Name}
foreach($folder in $folders_in_dir){
$joined_path=Join-Path -Path $check_dir_path -ChildPath $folder
#$joined_path2=Join-Path -Path '\\?\UNC\' -ChildPath $joined_path(tried not working)
#write-host $joined_path2
$files_sub = Get-ChildItem -Path $joined_path -Recurse
if($files_sub.count -gt 0){
$size_dir = ($files_sub | Measure-Object -Sum Length).Sum
Write-Host "$size_dir_padded $folder `r`n"
}
LOG1 (no issue):
size(bytes) file name
738621 PICK_PATH
2296972 TaskRand-Emailbuild
43961103 Task9-changetoTM1
11846548 Task10-linuxlogin
LOG2 (issue):
size(bytes) file name
62945815 BASS2 Rebase
24696625 JAZN-April04
Error messages:
Get-ChildItem : The given path's format is not supported.
At C:\BBBB_task\file_size_check.ps1:28 char:
+ $files_sub = Get-ChildItem -Path $joined_path -Recurse
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-ChildItem], NotSupportedException
+ FullyQualifiedErrorId : System.NotSupportedException,Microsoft.PowerShell.Commands.GetChildItemCommand
: ReadError: (\\slcnas463.us....rea\ADS30207754:String) [Get-ChildItem], PathTooLongException
+ FullyQualifiedErrorId : DirIOError,Microsoft.PowerShell.Commands.GetChildItemCommand
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 C:\gopala_task\file_size_check.ps1:28 char:14
+ $files_sub = Get-ChildItem -Path $joined_path -Recurse
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo
I am no expert with Powershell; however, I am trying to simply run an Invoke-Sqlcmd and save the results as a .csv file. I am looping through multiple *.sql files as the queries. When I run the following Powershell from a Windows10 desktop, everything runs fine but when I run this from our SQL Server, I am receiving errors on the export-csv command.
Here is my Powershell:
#Prompt for date
$DatePrompt = Read-Host -Prompt 'Enter the database date. (YYYY-MM-DD)'
#Convert to date
$DatabaseDate = [DateTime]::Parse($DatePrompt)
#Create FileDate string
$FileDate = $DatabaseDate.ToString("yyyyMMdd")
#Create SQLDate string
$SQLDate = $DatabaseDate.ToString("yyyy-MM-dd")
#--------------------------------------------------------------------------------------------------------------------------------
#Provide SQLServerName
$SQLServer ="SQLSERVER\MISDATA"
#Provide Database Name
$DatabaseName ="StagingDB"
#Set MonthStart and MonthEnd (YYYY-MM-DD)
$Variables = "FileDate = $SQLDate"
#Scripts Folder Path
$FolderPath ="\\SQLSERVER\MISDATA\Queries"
#Output Folder Path
$OutputFolderPath ="\\SQLSERVER\MISDATA\Results"
#--------------------------------------------------------------------------------------------------------------------------------
#Loop through the .sql files and run them
foreach ($filename in get-childitem -path $FolderPath -filter "*.sql")
{ #Run SQL Query
Invoke-Sqlcmd -ServerInstance $SQLServer -Database $DatabaseName -InputFile $filename.fullname -Variable $Variables -Querytimeout 0|
#Export to CSV
Export-Csv -NoTypeInformation -Path ($OutputFolderPath + "\" + $FileDate + "-" + $filename.basename + ".csv") -Encoding UTF8
#Write to ConsoleHost
Write-Host $filename.name "completed"
}
Here is the error:
Export-Csv : Cannot open file because the current provider (Microsoft.SqlServer.Management.PSProvider\SqlServer) cannot open a file.
At C:\MISDATA\Queries\Run Scripts.ps1:26 char:5
+ Export-Csv -NoTypeInformation -Path ($OutputFolderPath + "\" + $FileDate + " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Export-Csv], PSInvalidOperationException
+ FullyQualifiedErrorId : ReadWriteFileNotFileSystemProvider,Microsoft.PowerShell.Commands.ExportCsvCommand
sqlquery1.sql completed
Export-Csv : Cannot open file because the current provider (Microsoft.SqlServer.Management.PSProvider\SqlServer) cannot open a file.
At C:\MISDATA\Queries\Run Scripts.ps1:26 char:5
+ Export-Csv -NoTypeInformation -Path ($OutputFolderPath + "\" + $FileDate + " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Export-Csv], PSInvalidOperationException
+ FullyQualifiedErrorId : ReadWriteFileNotFileSystemProvider,Microsoft.PowerShell.Commands.ExportCsvCommand
sqlquery2.sql completed
Export-Csv : Cannot open file because the current provider (Microsoft.SqlServer.Management.PSProvider\SqlServer) cannot open a file.
At C:\MISDATA\Queries\Run Scripts.ps1:26 char:5
+ Export-Csv -NoTypeInformation -Path ($OutputFolderPath + "\" + $FileDate + " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Export-Csv], PSInvalidOperationException
+ FullyQualifiedErrorId : ReadWriteFileNotFileSystemProvider,Microsoft.PowerShell.Commands.ExportCsvCommand
sqlquery3.sql completed
You need to specify powershell ruled UNC format.
$OutputFolderPath ="Filesystem::\\SQLSERVER\MISDATA\Results"
or
$OutputFolderPath ="Microsoft.PowerShell.Core\FileSystem::\\SQLSERVER\MISDATA\Results"
I am working on azure CD pipeline, i want to change content of multiple files which exist in following folder structure.
MainFolder => SubFolder1 => myFile1.txt
SubFolder2 => myFile2.txt
SubFolder3 => myFile3.txt
I want to achieve my above requirement using powershell, and i have tried the following code.
$filepath = 'C:\Users\ashishjain06\Desktop\MainFolder'
$mydata = Get-ChildItem $filepath -include *.txt -recurse | Select-Object fullName
$totalRecords = $mydata.Count
for($x = 0; $x -lt $totalRecords; $x++)
{
((Get-Content -path $mydata[$x] -Force) -replace 'oldText','newText') | Set-Content -Path $mydata[$x]
}
When i run above code it's give me following output.
Get-Content : Cannot find drive. A drive with the name '#{FullName=C' does not exist.
At line:6 char:7
+ ((Get-Content -path $mydata[$x] -Force) -replace 'oldText ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (#{FullName=C:String) [Get-Content], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetContentCommand
Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:6 char:25
+ ((Get-Content -path $mydata[$x] -Force) -replace 'oldText ...
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand
Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:6 char:25
+ ((Get-Content -path $mydata[$x] -Force) -replace 'oldText ...
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand
Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:6 char:25
+ ((Get-Content -path $mydata[$x] -Force) -replace 'oldText ...
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand
Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:6 char:25
+ ((Get-Content -path $mydata[$x] -Force) -replace 'oldText ...
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand
I am newbie on powershell, Please help me out to resolve this issue.
Get-ChildIItem returns (an array of) FileInfoObjects with a bunch of properties,
Select-Object drops all but the selected one, but it is still an object with one property FullName.
See $mydata | Get-Member
One method is Select-Object -ExpandProperty FullName,
another one is the property dereference operator . used in the following script.
To have the script work on any user don't include a fixed path, either use $Env:USERPROFILE or better yet, let the system evaluate current users Desktop folder (which might be relocated).
Instead of iterating the arrray $mydata by index let powershell do that with a foreach:
$filepath = Join-Path ([environment]::GetFolderPath('Desktop')) 'MainFolder'
$files = (Get-ChildItem $filepath -Filter *.txt -Recurse).FullName
foreach($file in $files){
(Get-Content -path $file -Force) -replace 'oldText','newText' | Set-Content -Path $file
}
It's still an object with a property unless you do this:
select-object -expandproperty fullname
Replace Select-Object with ForEach-Object, i.e.:
$filepath = 'C:\Users\ashishjain06\Desktop\MainFolder'
#$mydata = Get-ChildItem $filepath -include *.txt -recurse | Select-Object fullName
$mydata = Get-ChildItem $filepath -include *.txt -recurse | ForEach-Object fullName
$totalRecords = $mydata.Count
for($x = 0; $x -lt $totalRecords; $x++)
{
((Get-Content -path $mydata[$x] -Force) -replace 'oldText','newText') | Set-Content -Path $mydata[$x]
}
I am hoping someone can give me the push I need to get this done, but I have had no luck with this exact situation online.
I need to use PowerShell (unfortunately I can't use Python or .NET to so this:( ) to parse though a list of files to determine if they contain a line termination of /r rather than /r/n. This script was previously in production and working, when single files were passed.
I am making adjustments so that multiple files can be accommodated.
I am getting the list of filenames and putting them into an array (which is working) but when I tey to loop the files through the if statement I get this error.
Here is my code:
param(
#[Parameter(Mandatory=$True)]
[String]$FileName = "C:\LineTermTest\*C*.txt"
)
$FileNameArray = Get-ChildItem -Path $FileName | where {!$_.psicontainter }| Select-Object fullname
for ($i=0; $i -le $FileNameArray.Length -1; $i++ )
{
$File = $FileNameArray[$i]
if (Get-Content -path $File -Delimiter "`0" | Select-String "[^`r]`n" )
{
$content = Get-Content $File
$content | Set-Content $File -Replace "`n", "'r'n" -Encoding ASCII
[gc]::collect()
[gc]::WaitForPendingFinalizers()
}
}
and here is the error I get
Get-Content : A parameter cannot be found that matches parameter name 'Delimiter'.
At line:13 char:39
+ if (Get-Content -path $File -Delimiter <<<< "0" | Select-String "[^r]`n" )
+ CategoryInfo : InvalidArgument: (:) [Get-Content], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetContentCommand
Get-Content : A parameter cannot be found that matches parameter name 'Delimiter'.
At line:13 char:39
+ if (Get-Content -path $File -Delimiter <<<< "0" | Select-String "[^r]`n" )
+ CategoryInfo : InvalidArgument: (:) [Get-Content], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetContentCommand
Get-Content : A parameter cannot be found that matches parameter name 'Delimiter'.
At line:13 char:39
+ if (Get-Content -path $File -Delimiter <<<< "0" | Select-String "[^r]`n" )
+ CategoryInfo : InvalidArgument: (:) [Get-Content], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetContentCommand
in your script, $File is a 'PSCustomObject', not a FileInfo object, so you need to use its property 'fullname' like this: Get-Content -path $File.fullname -Delimiter "`0". This is because the objects in $FileNameArray are created by using Select-Object.
You can avoid this by leaving out "| Select-Object fullname" when creating $FileNameArray. That way, the $FileNameArray contains FileInfo objects, and Get-Content can use those directly. This is the preferred way.
So this line:
$FileNameArray = Get-ChildItem -Path $FileName | where {!$_.psicontainter }| Select-Object fullname
becomes this line:
$FileNameArray = Get-ChildItem -Path $FileName | where {!$_.psicontainter }
I tried to do like this but not works, any ideas?
if(Test-Path ~\desktop){
$bigfiles = Get-ChildItem ~\desktop -force -Include *.* | Where-Object {$_.Length -gt 10GB}
if{$bigfiles -gt 10GB){
echo "You have big files"
}
}
this is the error:
Cannot compare "C:\Users\mario\Desktop\AngelinaJolie_photo_in_4k.jpg" because it is not IComparable.
At line:7 char:8
+ if($bigfiles -gt 10GB){
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NotIcomparable
$bigfiles is $null if there are no results, a FileInfo if there is one result, otherwise it is an array of FileInfos. You can check for results using
if($bigfiles) { ... }