Hello I am new scripting, I am tasked with creating a script that will be deleting a file from specific folders which will be deployed through SCCM onto many computers.
The problem is I want to output the log file saying either:
"<ComputerName> File Terminated"
"<ComputerName> File Not terminated"
Here is what I have so far:
$users = "C:\Users"
$logFile = "C:\TTS\Logs\GoogleTerm.log"
$source = "\AppData\Roaming\Google"
$exclude = "Default"
$input = get-ChildItem -Path $users
foreach ($folder in $input) {
if ($exclude -notcontains $folder.Name) {
Remove-Item -Path ($Users + "\" + $folder.Name + $source) -recurse -force
}
}
echo "Google Terminated on:"$env:computername >> $logfile
Added an else to your if to handle both outcomes, and then using Add-Content instead of echo:
foreach ($folder in $input) {
if ($exclude -notcontains $folder.Name) {
Remove-Item -Path ($Users + "\" + $folder.Name + $source) -recurse -force
Add-Content $logfile "$env:computername File Terminated"
}
else {
Add-Content $logfile "$env:computername File Not Terminated"
}
}
Add-Content $logfile "Google Terminated on: $env:computername"
This was my successfull solution, thank you guys for the assistance!
$users = "C:\Users"
$logFile = "C:\TTS\Logs\GoogleTerm.log"
$exclude = "Default"
$input = get-ChildItem -Path $users
foreach ($folder in $input) {
if ($exclude -notcontains $folder.Name) {
if (Test-Path ($Users + "\" + $folder.Name + $source)){
Remove-Item -Path ($Users + "\" + $folder.Name + $source) -recurse -force
Add-Content $logFile "Google Terminated on: $env:computername UserName:$folder "
}
else{
Add-Content $logFile "Google Already Terminated on:$env:computername UserName:$folder "
}
}
else{
Add-Content $logFile "Not Terminated on: $env:computername Username:$folder"
}
}
Related
I'm trying to create a powershell script which checks a log file for lines of text and if the line exists restarts a service and resets/archives the log. I got it working before with 1 "checkstring" if you will, but I've been struggling to get it to work with a list of strings. Could anyone help me figure out where I'm going wrong?
This is the code I'm currently using:
$serviceName = "MySQL80"
$file = "test.txt"
$pwd = "C:\tmp\"
$checkStrings = New-Object System.Collections.ArrayList
# Add amount of checkstrings
$checkStrings.add("Unhandled error. Error message: Error retrieving response.")
$checkStrings.add("Unhandled error. Error message: Error retrieving response. Second")
$logName = "ServiceCheck.log"
$backupFolder = "Archive"
$logString = (Get-Date).ToString("ddMMyyyyHHmmss"), " - The service has been reset and the log moved to backup" -Join ""
Set-Location -Path $pwd
if(Test-Path -Path $file) {
if(Test-Path -Path $backupFolder) {
} else {
New-Item -Path $pwd -Name $backupFolder -ItemType "director"
}
foreach ($element in $checkStrings) {
$containsWord = $fileContent | %{$_ -match $element}
if ($containsWord -contains $true) {
Restart-Service -Name $serviceName
$backupPath = $pwd, "\", $backupFolder, "\", $date, ".log" -join ""
$currentFile = $pwd, "\", $file -join ""
Copy-Item $currentFile -Destination $backupPath
Get-Content $currentFile | select-string -pattern $checkString -notmatch | Out-File $currentFile
if(Test-Path -Path $logName) {
Add-Content $logName $logString
} else {
$logString | Out-File -FilePath $logName
}
}
}
}
Script is working almost how it is intended, still struggling with renaming duplicate files. I cannot figure out how to get it to name the files like
filename(1).ext
filename(2).ext
the closest I have gotten was
filename(1).ext
filename(1)(2).ext
#region actual script
$srcRoot = "C:\srcLocation"
$dstRoot = "C:\dstLocation"
$fileList = Get-ChildItem -Path $srcRoot -File -Force -Recurse
foreach ($file in $fileList) {
$fileName = $file.Name.ToUpper()
$fileExt = $file.Extension.ToUpper()
$dstFileName = $null
switch -Regex ($fileName)
{
'[A-Z]{4}-[0-9]{3}' { $dstFileName = $fileName }
'[A-Z]{4} [0-9]{3}' { $dstFileName = $fileName -replace '([A-Z]{4})\s([0-
9]{3})','$1-$2' }
'[A-Z]{4}[0-9]{3}' { $dstFileName = $fileName -replace '([A-Z]{4})([0-9]
{3})','$1-$2'}
Default { Write-Warning -Message "$fileName is not an expected filename"
}
}
if ($dstFileName) {
$dstDir = $dstFileName.Split('.')[0].Substring(0,8)
$dstPath = Join-Path -Path $dstRoot -ChildPath $dstDir
if (-not (Test-Path -Path $dstPath)) {
New-Item -Path $dstPath -ItemType Directory
}
$i = 1
if (test-path $dstPath\$dstFileName){
$dstFileName = $dstFileName.Split('.')[0] + "($i)" + $fileExt
While (test-path $dstPath\$dstFileName){
$i +=1
$dstFileName = $dstFileName -replace
}
}
Write-Verbose "Moving $($file.FullName)"
Move-Item -Path $($file.FullName) -Destination $dstPath\$dstFileName -
ErrorAction Continue
}
}
#endregion
You can simply use the Replace method of string objects in PowerShell. To verify your input, you can use a RegEx. Move-Item will throw an error, if the file already exists in the destination anyways. The complete script would look like this.
#region setup
New-Item -Path C:\srcpath,C:\dstpath -ItemType Directory
Set-Location C:\srcpath
New-Item 'ABCD123.txt','ABCD 123.txt','AbCD-123.txt','AAAA111.txt','BBBB 222.jpg','BBBB-222.txt' -ItemType File
#endregion
#region actual script
$srcRoot = "C:\srcpath"
$dstRoot = "C:\dstpath"
$fileList = Get-ChildItem -Path $srcRoot -File -Force -Recurse
foreach ($file in $fileList) {
$fileName = $file.Name.ToUpper()
$dstFileName = $null
switch -Regex ($fileName)
{
'[A-Z]{4}-[0-9]{3}' { $dstFileName = $fileName }
'[A-Z]{4} [0-9]{3}' { $dstFileName = $fileName -replace '([A-Z]{4})\s([0-9]{3})','$1-$2' }
'[A-Z]{4}[0-9]{3}' { $dstFileName = $fileName -replace '([A-Z]{4})([0-9]{3})','$1-$2'}
Default { Write-Warning -Message "$fileName is not an expected filename" }
}
if ($dstFileName) {
$dstDir = $dstFileName.Split('.')[0]
$dstPath = Join-Path -Path $dstRoot -ChildPath $dstDir
if (-not (Test-Path -Path $dstPath)) {
New-Item -Path $dstPath -ItemType Directory
}
Write-Verbose "Moving $($file.FullName)"
Move-Item -Path $($file.FullName) -Destination $dstPath\$dstFileName -ErrorAction Continue
}
}
#endregion
#region result
Write-Host '----- Result -----' -BackgroundColor DarkYellow
Get-ChildItem C:\dstpath -Recurse | Select-Object -ExpandProperty FullName
#endregion
Gets the Files in Source folder (Get-ChildItems)
Renames The File to include a - instead of a " " (Rename-Item)
Sets the Child Name property to the new name ($File.Name)
Creates new Folder in source based on first 4 Chars
Moves-Item to new created folder (move-item)
$Source = "C:\Start"
$Destination = "C:\End"
foreach($File in (Get-ChildItem -Path $Source -File -Recurse)){
Rename-Item $File.Fullname ($File.Name -replace " ", "-")
$file.Name = ($File.Name -replace " ", "-")
New-Item "$($Destination)\$($File.Name.Substring(0,3))" -ItemType directory
move-item $File.FullName -force -destination $Destination\$($File.Name.Substring(0,3))
}
I have a powershell script that copies a file to a remote computer, and I need to execute it from a command line and with arguments/parameters.
Here is what I have...and I can't get it to work:
Get-Content C:/temp/list.txt |
ForEach-Object {
Try {
$source = "\\server\folder\my application 1.2.1.EXE"
$destination = "\\" + $_ + "\C$\temp\"
New-Item -Path $destination -ItemType Directory -Force
Copy-Item -path $source -Destination $destination -force | Out-Null
& "$_ +"\C:\temp\my application 1.2.1.EXE" Location=07 /s" ##| Out-Null
$status = "Success"
}
Catch {
$status = "Failed"
}
"$_, $status" | out-file -filepath c:\temp\restult1.csv -Append -Encoding ascii
}
I resolved it.
Get-Content C:/temp/list.txt |
ForEach-Object {
Try {
$source = "\\server\folder\my application 1.2.1.EXE"
$destination = "\\" + $_ + "\C$\temp\"
New-Item -Path $destination -ItemType Directory -Force
Copy-Item -path $source -Destination $destination -force | Out-Null
Invoke-Command -ComputerName $_ -ScriptBlock {
& cmd.exe /c "C:\temp\my application 1.2.1.EXE" Location=07 /s ##| Out-Null
}
$file = $destination + "my application 1.2.1.EXE"
Remove-Item $file -Force
$status = "Success"
}
Catch {
$status = "Failed"
}
"$_, $status" | out-file -filepath c:\temp\restult1.csv -Append -Encoding ascii
}
I searched, i googled.. about to smash my head on the table
how come this will not work?
move-Item $path$file $targetdir
it gives me an error
Move-Item : An object at the specified path C:\Repository\test.csv
does not exist.
now if i debug this and i output using
write-output move-Item $path$file $targetdir
and take that output and paste it (file name with path and destination) it works!
and trust me the file is there. =\
Code below
$path = 'C:\test\'
$TimeStamp = Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
$LogFile = Get-Date -Format "MM_dd_yyyy"
$targetdir = "C:\test\Uploaded\"
#Get-ChildItem -path $path\* -Include *.csv | foreach-object {$_.Fullname} | Format-Table name -hidetableheaders | Out-File $path\list.txt
Get-ChildItem -path $path\* -Include *.csv | Format-Table name -hidetableheaders | Out-File $path\list2.txt
get-content C:\test\list2.txt | where {$_ -ne ""} | out-file C:\test\list.txt
Remove-Item C:\test\list2.txt
$list = get-content C:\test\list.txt
foreach ($file in $list)
{
$ftp = "ftp://REMOVED/$file"
"ftp url: $ftp"
$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)
"Uploading $file..."
$succeeded = $true;
& {
trap { $script:succeeded = $false; continue }
$webclient.UploadFile($uri, $path+$file)
}
if ($succeeded)
{
echo $file 'Was successfully uploaded!' $Timestamp >> logfile$LogFile.log
move-Item -path $path$file -destination $targetdir
#test-path $path$file
}
else
{
echo $file 'Was not successfully uploaded, will retry later' $Timestamp >> logfile$LogFile.log
}
}
exit
Basics are:
Test-Path before you move it (file and destination)
Move the file, ensure you have permission (force it to move)
so:
echo $targetdir
echo "$path$file"
if (!(Test-Path $targetdir)) {
New-Item -ItemType directory $targetdir
}
if(Test-Path "$path$file") {
Move-Item "$path$file" $targetdir -Force
} else {
echo "file does not exist"
}
If you loop over a collection you have to use the ".FullName" property of the object:
Get-ChildItem $path | ForEach-Object { Move-Item $_.FullName $targetdir -Force }
Does the target directory already exist? I believe Move-Item will fail if the target directory doesn't exist. If that's the case, you can simply test for existence of the directory beforehand and then create as necessary.
If (!(Test-Path -Path $targetdir)) {
New-Item -ItemType directory -Path $targetdir
}
This worked for me. Thank you #TheMadTechnician. Hopes this helps everyone
$TimeStamp = Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
$LogFile = Get-Date -Format "MM_dd_yyyy"
$path='C:\test\'
$targetDir = 'C:\test\Uploaded\'
$fileList = Get-ChildItem $path*.csv
If(!(Test-Path $TargetDir)){New-Item -ItemType Directory -Path $TargetDir|Out-Null}
$fileList | Select -ExpandProperty Name | Out-File 'C:\test\list.txt'
$list = get-content C:\test\list.txt
foreach ($file in $list)
{
$ftp = "ftp://REMOVED/$file"
"ftp url: $ftp"
$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)
"Uploading $file..."
$succeeded = $true;
& {
trap { $script:succeeded = $false; continue }
$webclient.UploadFile($uri, $path+$file)
}
if ($succeeded)
{
echo $file 'Was successfully uploaded!' $Timestamp >> logfile$LogFile.log
move-Item -path $path$file -destination $targetdir$Timestamp"_"$file
#test-path $path$file
}
else
{
echo $file 'Was not successfully uploaded, will retry later' $Timestamp >> logfile$LogFile.log
}
}
exit
How about this then:
ForEach($File in $List){
Join-Path $path $file | Move-Item -Dest $Targetdir
}
Edit: Also... your creation of list.txt, it bothered me so I had to comment. Format-Table should be used for formatting text, not for selecting a value to output to a file. There's a better way to do that, consider this alternative:
Get-ChildItem "$path*.csv" | Select -ExpandProperty Name | Out-File $pathlist.txt
Since you say that $path = 'C:\test\' you are adding extra backslashes in there that may cause issues for some commands.
Edit2: Ok, if that doesn't work, why not work with the files themselves instead of outputting to a file, importing from that file, and then working with things.
$path='c:\test\'
$TargetDir = 'c:\test\NewDir'
$FileList = Get-ChildItem $path*.csv
If(!(Test-Path $TargetDir)){New-Item -ItemType Directory -Path $TargetDir|Out-Null}
$FileList | Move-Item -Destination $TargetDir
Then if you really want a list of those file names just pipe $FileList to Select and then to Out-File
$FileList | Select -ExpandProperty Name | Out-File 'C:\Test\list.txt'
Here, look through this and see if there's anything you like. I made a few changes, such as declaring paths at the beginning for everything, I moved the WebClient object creation outside of the loop, and changed how things are displayed on screen. Plus I skip the entire exporting to text file and re-importing it.
$path = 'C:\test'
$ftpaddr = 'ftp://ftp.example.com/uploads'
$TimeStamp = Get-Date -Format "MM/dd/yyyy hh:mm:ss tt"
$LogFile = Get-Date -Format "MM_dd_yyyy"
$LogDir = "C:\Test\Logs"
If(!(test-path $LogDir)){New-Item -ItemType Directory -Path $LogDir | Out-Null}
$targetdir = 'C:\test\Uploaded'
If(!(test-path $targetdir)){New-Item -ItemType Directory -Path $targetdir | Out-Null}
$list = Get-ChildItem -path $path\* -Include *.csv
$webclient = New-Object System.Net.WebClient
"ftp url: $ftpaddr"
foreach ($file in ($list|select -ExpandProperty Name))
{
$uri = New-Object System.Uri(("$ftpaddr/$file"))
Write-Host "Uploading $file... " -NoNewline -ForegroundColor White
$succeeded = $true
& {
trap { $script:succeeded = $false; continue }
$webclient.UploadFile($uri, "$Path\$file")
}
if ($succeeded)
{
Write-Host "Success!" -ForegroundColor Green
"$Timestamp`t$File was successfully uploaded!" | Out-File "$logdir\logfile$LogFile.log" -Append
move-Item -path "$path\$file" -destination $targetdir
}
else
{
Write-Host "Failed! Will retry later." -ForegroundColor Red
"$Timestamp`t$File was not successfully uploaded, will retry later" | Out-File "$logdir\logfile$LogFile.log" -Append
}
}
I've just started working with PowerShell and with a bit of help from a book and a lot of Google searching I've come up with this script. The problem I'm having is that it isn't keep the folder structure. It is checking one network location for files that are over 5 days old. If it is older than 5 days, it moves it to a different network location. At the second location it checks for files over 30 days old and deletes those files.
$movepath = "C:\test"
$archpath = "C:\test2"
$deletepath = "C:\files"
$movedays = "5"
$deletedays = "30"
$datetime = get-date
$deletelog = "c:\logs\deletelog.txt"
$movelog = "c:\logs\movelog.txt"
$errorlog = "c:\logs\errorlog.txt"
write-progress -activity "Archiving Data" -status "Progress:"
Get-Childitem -Path $movepath -Recurse | Where-Object {$_.LastWriteTime -lt (get-date).AddDays(-$movedays)} |
ForEach {
$filename = $_.fullname
try
{
Move-Item $_.FullName -destination $archpath -force -ErrorAction:SilentlyContinue
"Moved $filename to $archpath at $datetime successfully" | add-content $movelog
}
catch
{
"Error moving $filename: $_ " | add-content $errorlog
}
}
Get-Childitem -Path $deletepath | Where-Object {$_.LastWriteTime -lt (get-date).AddDays(-$deletedays)} |
ForEach {
$filename = $_.fullname
try
{
Remove-Item $_.FullName -force -ErrorAction:SilentlyContinue
"Removed $filename at $datetime successfully" | add-content $deletelog
}
catch
{
"Error moving $filename: $_ " | add-content $errorlog
}
}
You need to add in logic to maintain the folder structure.
$FileName = $_.FullName.Replace($MovePath, $ArchPath);