I want to take a text file with usernames, and then search a specific location (UNC path) and return any matches found, outputting them to a log file:
#Searches target folder for all folders matching input
$start = (get-date -uformat "%Y-%m-%d_%H%M")
$defaultLogFileName = "folder_matcher" + $start + ".log"
#Log file header
$header = #()
$header += "=============================="
$header += "Search results"
$header += ""
$header += "Execution Start: " + (get-date -uformat "%Y-%m-%d %H%M") + ""
$header += ""
#Get the logfile location
do
{
$logdir = Read-Host "Enter log directory (or press Enter for default c:\)"
if ($logdir -eq "")
{$logfile = ("c:\" + $defaultLogFileName); break;}
if(Test-Path $logdir)
{$logfile += ($logdir + "\" + $defaultLogFileName); break;}
Write-Host -ForegroundColor Red "Directory does not exist"
} while (!(Test-Path $logfile))
$SourceFile = Read-Host "Enter file path"
$SearchValue = Read-host "Enter target directory to sweep"
$header | Out-File -FilePath $logfile
foreach($user in $sourcefile){
Get-ChildItem $SearchValue -filter $user | Out-file -Append -FilePath $logfile
}
When I attempt to use Get-ChildItem in this loop, this is the result:
Get-ChildItem : Second path fragment must not be a drive or UNC name.
Parameter name: path2
At \\erebus\erebus_users$\rraymond1\ps\searchandmatch.ps1:32 char:14
+ Get-ChildItem <<<< $SearchValue -filter $user | Out-file -Append -FilePath $logfile
+ CategoryInfo : InvalidArgument: (\\harvard\tsprofiles$:String)
[Get-ChildItem], ArgumentException + FullyQualifiedErrorId DirArgumentError,Microsoft.PowerShell.Commands.GetChildItemCommand
I have tried replacing the variables with fixed values (even mapping the UNC path locally and trying to run it that way), and the problem remains. How can I fix it?
Related
I will upload file under folder onTeams with PowerShell. I am using some try/catch block inside if/else statement. How can we improve my script? Or what do you recommend? I want to know is whether there is any way to make this code run better. I'm new to Powershell, so I don't know what looks like bad code or good code.
Let's say, I've run my script in November 2022. It will create a folder called 2022-10 under "/sites/Team/Shared Documents/General/Documents/2022"
Or I've run my script in February 2023. Firstly, it will create called 2023 mail folder for new year under "/sites/Team/Shared Documents/General/Documents/ Then it will create folder called 2023-01 under "/sites/Team/Shared Documents/General/Documents/2023"
And so on.
My script:
#Config Variables
$SiteURL = "https://company.sharepoint.com/sites/Team"
$SourceFilePath ="C:\Documents\report.csv"
$DestinationFolderPath = "/sites/Team/Shared Documents/General/Documents" #Server Relative URL
Try {
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -ClientId "47bf0ca0-1d8a-xxxx-xxx-xxxx" -Tenant 'tenant.onmicrosoft.com' -Thumbprint <Thumbprint>
}
catch {
write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}
$year= get-date -Format yyyy
$FolderURL = $DestinationFolderPath + "/" + $year
#Try to Get the Folder
$Folder = Get-PnPFolder -Url $FolderURL -ErrorAction SilentlyContinue
#sharepoint online powershell To check if folder exists
If($Folder -ne $null)
{
Write-Host -f Green "Folder exists!"
Try{
$d = (get-date).AddMonths(-1).ToString("yyyy-M")
$FolderPATHLastMonth = $DestinationFolderPath + "/" + $year
Add-PnPFolder -Name $d -Folder $FolderPATHLastMonth
$DestinationFolderPath = $FolderPATHLastMonth + "/" + $d
Add-PnPFile -Path $SourceFilePath -Folder $DestinationFolderPath -ErrorAction Stop
}
catch{
echo $_.Exception
}
}
Else
{
Write-Host -f Yellow "Folder does not exists!"
Try{
Add-PnPFolder -Name $year -Folder $DestinationFolderPath
$d2 = (get-date).AddMonths(-1).ToString("yyyy-M")
$FolderPATHLastMonth = $DestinationFolderPath + "/" + $year
Add-PnPFolder -Name $d2 -Folder $FolderPATHLastMonth
$DestinationFolderPath = $FolderPATHLastMonth + "/" + $d2
Add-PnPFile -Path $SourceFilePath -Folder $DestinationFolderPath -ErrorAction Stop
}
catch{
echo $_.Exception
}
}
I am a beginner at powershell script and I am stuck
I am trying to upload 2 xml files with the same name to FTP, but I am getting the following error
Exception calling "UploadFile" with "2" argument(s): "An
exception occurred during a WebClient request." At
C:\powershell\ExternalWidgets\upload-to-ftp.ps1:51 char:16
+ $webclient.UploadFile($uri.AbsoluteUri, $LocalPath)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException`
Here is the script:
#SET CREDENTIALS
$credentials = new-object System.Net.NetworkCredential($user, $pass)
cd $target
$DirectoryContent = Get-ChildItem -Directory
foreach($item in $DirectoryContent){
cd $item
$currentFolderItems = Get-ChildItem
foreach( $subfolderItem in $currentFolderItems)
{
if ($subfolderItem.name -eq "package.json") {
$subItem = Get-ChildItem -Directory
foreach($subItem in $subItem)
{
if ($subItem.name -eq "coverage") {
$files = Get-ChildItem -Path $subItem
$n = 0
foreach ($file in $files)
{
#rename coverage file
if($file.Name -eq "cobertura-coverage.xml") {
$newFileName=$file.Name.Replace("cobertura-coverage.xml","cobertura-coverage$n.xml")
Rename-Item $file -NewName $newFileName
$newFileName
}
$n++
}
}
}
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object
System.Net.NetworkCredential($user,$pass)
$uri = New-Object System.Uri($ftp + "/" + $folder)
#Delete files from FTP
# $fileUploaded =($uri + "\" + $newFileName)
# $fileUploaded
# Remove-Item $fileUploaded
$LocalPath =($target + "\" + $item + "\" + "coverage" + "\" +
$newFileName).Replace(".\", "").Replace('\', '/')
$webclient.UploadFile($uri, $LocalPath)
#cd..
}
}
cd ..
}
I also get an error when I want to rename one of the files. What step am I missing? Thank you
I am trying to add 400 computer to a collection and I have an error running the powershell in SCCM. I try to change the . to _ but also encounter the same error.
Method invocation failed because [System.Char] does not contain a method named 'Split'.
At line:8 char:5
+ $collectionname = $filenames.Name[$x].Split(".")[0]
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Powershell:
#Set path to collection directory
$collectiondir = "D:\Collections\"
#Pull only .TXT files into array
$filenames = Get-ChildItem $collectiondir* -include *.txt
for ($x=0; $x -lt ($filenames.Length); $x++) {
$collectionname = $filenames.Name[$x].Split(".")[0]
$collectionname
#Add new collection based on the file name
try {
New-CMDeviceCollection -Name $collectionname -LimitingCollectionName "All Systems"
}
catch {
"Error creating collection - collection may already exist: $collectionname" | Out-File "$collectiondir\$collectionname`_invalid.log" -Append
}
#Read list of computers from the text file
$computers = Get-Content $filenames[$x]
foreach($computer in $computers) {
try {
Add-CMDeviceCollectionDirectMembershipRule -CollectionName $collectionname -ResourceId $(get-cmdevice -Name $computer).ResourceID
}
catch {
"Invalid client or direct membership rule may already exist: $computer" | Out-File "$collectiondir\$collectionname`_invalid.log" -Append
}
}
}
You must have made a mistake following my hints, both do work:
$collectiondir = "D:\Collections\"
#Pull only .TXT files into array
$filenames = Get-ChildItem -Path $collectiondir -Filter *.txt
for ($x=0; $x -lt ($filenames.Length); $x++) {
$collectionname = $filenames[$x].Name.Split(".")[0]
$collectionname
}
"-----"
ForEach ($file in $filenames){
$collectionname = $file.Name.Split(".")[0]
$collectionname
}
If you wanted to split the extension a better way is to simply use BaseName instead of Name
Need Batch or Powershell script to find some files by its content (xls file with some string) and then upload to ftp server.
###########################################################
$Path = "f:/temp"
$Text = "123456"
$PathArray = #()
$Results = "F:/PROFIT/INSTALL/backup/search/test.txt"
# This code snippet gets all the files in $Path that end in ".txt".
Get-ChildItem $Path -Filter "*.txt" -Recurse|
Where-Object { $_.Attributes -ne "Directory"} |
ForEach-Object {
If (Get-Content $_.FullName | Select-String -Pattern $Text) {
$PathArray += $_.FullName
$PathArray | % {$_} | Out-File $Results
}
}
Write-Host "Contents of ArrayPath:"
$PathArray | ForEach-Object {$_}
#we specify the directory where all files that we want to upload
$Dir="F:/PROFIT/INSTALL/backup/search"
#ftp server
$ftp = "ftp://127.0.0.1"
$user = "ftp"
$pass = "ftp"
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
#list every sql server trace file
foreach($item in (dir $Dir "*.*")){
"Uploading $item..."
$uri = New-Object System.Uri($ftp+$item.Name)
$webclient.UploadFile($uri, $item.FullName)
}
Tried this, but each time have a problem:
Uploading test.txt... Исключение при вызове "UploadFile" с "2"
аргументами: "Невозможно разрешить уда ленное имя:
'127.0.0.1test.txt'" F:\PROFIT\INSTALL\backup\search\search.ps1:36
знак:5
+ $webclient.UploadFile($uri, $item.FullName)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
You have an error on concatenation of server and file name. Try Something like this :
#variables
$PathToSearch = "c:\temp"
$SearchText = "hello"
$Results = "c:\temp\test.txt"
$ftp = "ftp://127.0.0.1/"
$user = "ftp"
$pass = "ftp"
#get liste file to found with string
$PathArray=Get-ChildItem $PathToSearch -Filter "*.txt" -Recurse -file | Select-String -Pattern $SearchText | get-item | select Name, FullName
Write-Host "Files founded :"
$PathArray.FullName
#send to ftp server
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
$PathArray | % {
$uri = New-Object System.Uri($ftp+$_.Name)
$webclient.UploadFile($uri, $_.FullName)
$_.FullName | Out-File -FilePath $Results -Append
}
$webclient.Dispose()
I'm working on a script to rename files based on EXIF data.
param([string]$path)
# http://blogs.technet.com/b/jamesone/archive/2007/07/13/exploring-photographic-exif-data-using-powershell-of-course.aspx
[reflection.assembly]::loadfile( "C:\Windows\Microsoft.NET\Framework\v2.0.50727\System.Drawing.dll") | out-null
function MakeString {
$s=""
for ($i=0 ; $i -le $args[0].value.length; $i ++) {
$s = $s + [char]$args[0].value[$i]
}
return $s
}
$files = Get-ChildItem -Path $path
foreach ($file in $files) {
if ($file.Extension -ne ".jpg") { continue }
if ($file.Name -match "^(\d+)-(\d+)-(\d+)") { continue }
$exif = New-Object -TypeName system.drawing.bitmap -ArgumentList $file.FullName
$captureDate = MakeString $exif.GetPropertyItem(36867)
$captureDate = ($captureDate -replace ":", '-').Substring(0,19)
$newFilename = $captureDate + " " + $file.Name.Trim()
$file.Name + " -> " + $newFilename
$file |Rename-Item -NewName $newFilename
}
Reading the date from EXIF is no problem, but when I try to rename the file I get this error message:
Rename-Item : The process cannot access the file because it is being used by another process.
At D:\Norwegen\RenamePhotos.ps1:25 char:12
+ $file |Rename-Item -NewName $newFilename
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (D:\Norwegen\P1270465 (1920x1433).jpg:String) [Rename-Item], IOException
+ FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand
When I monitor the directory in ProcMon I can see that the files are closed rather late:
(look at the highlighted line, it's from an earlier file in the middle of the entries from the file currently being processed)
So, how can I close the file (which is probably still open from the EXIF read) so I can rename it?
What I already tried to close the open file:
Remove-Variable exif
$file.Close()
Since you only read from the the file, then a call to Dispose() should do the trick. Ex.
foreach ($file in $files) {
if ($file.Extension -ne ".jpg") { continue }
if ($file.Name -match "^(\d+)-(\d+)-(\d+)") { continue }
$exif = New-Object -TypeName system.drawing.bitmap -ArgumentList $file.FullName
$captureDate = MakeString $exif.GetPropertyItem(36867)
#Disposing object as soon as possible
$exif.Dispose()
$captureDate = ($captureDate -replace ":", '-').Substring(0,19)
$newFilename = $captureDate + " " + $file.Name.Trim()
$file.Name + " -> " + $newFilename
$file |Rename-Item -NewName $newFilename
}