How To Create A Log For Failed Events - windows

I have a very simple PowerShell script where I am copying data that's in one folder, and is putting it on an external hard drive. I would like to create a log file for failed events (meaning if some of the data was not copied) The data can be a .txt file. Here is the simple log file I have.
Set-ExecutionPolicy Unrestricted -Force
Copy-Item -Path C:\Program Files (x86)\Cummins Allisson\TempData\iFX1\* -Destination D:\backup -recurse
Set-ExecutionPolicy Unrestricted -Force
Remove-Item C:\Program Files (x86)\Cummins Allison\TempData\iFX1\* -recurse
I appreciate the help on this. I am very new to PowerShell and by no means an expert.
Thanks again

You could use the common parameters -ErrorAction and -ErrorVariable to assist you in this.
Copy-Item -Path C:\Program Files (x86)\Cummins Allisson\TempData\iFX1\* -Destination D:\backup -recurse -ErrorAction SilentlyContinue -ErrorVariable events
Remove-Item C:\Program Files (x86)\Cummins Allison\TempData\iFX1\* -recurse -ErrorAction SilentlyContinue -ErrorVariable events
Then you will have the variable $events which will contain all the details of the errors that occurred for both of those commands. SilentlyContinue surpresses the error output from the screen which, in addition to being stored in the default variable $error is stored in $events.
$events.Exception | Set-Content c:\temp\log.log
This would give you sample data like
An item with the specified name C:\temp\data2\data already exists.
An item with the specified name C:\temp\data2\data\folder1 already exists.
An item with the specified name C:\temp\data2\data\folder1\folder2 already
exists.
Which only happened since I didn't use the -Force parameter for Copy-Item which would have overwritten the files.
Side Note
I should think you would be able to use Move-Item for this code as well.
Depeding on how ofter this code is run in the same session you might need to set the variable $events to $null or equivalent so you don't get duplicate output.

Related

Locate Registry Key and delete value

I am trying to delete a binary value within my registry with this code the code prompts an error stating the value at DefaultConnectionSettings does exist but it's able to find the SID path, but not the exact DefaultConnectionSettings Value. I'm running this script on a test machine that has the DefaultConnectionSettings.
RegEdit.exe screenshot
Any input would be helpful Thanks,
if (!(Test-Path 'HKU:\')) {
New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS
}
($path = Get-ChildItem -Path 'HKU:\*\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections' -ErrorAction SilentlyContinue) |
ForEach-Object { Remove-ItemProperty -Path $path -name "DefaultConnectionSettings" -force }
The registry value you're trying to delete is a value of the registry::HKEY_USERS\*\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections registry keys themselves.
Note that you can target the HKEY_USERS hive simply by prepending the provider prefix registry:: to the native registry path - no need to map a new drive with New-PSDrive first.
By contrast, Get-ChildItem looks for subkeys of the targeted keys.
Note that registry values are considered properties of registry keys, not child items (the way that files are in the file-system).
Thus, the immediate fix is to switch from Get-ChildItem to Get-Item, which returns objects representing the target keys themselves.
However, you can do it all with a single Remove-ItemProperty call (as with your own attempt, running from an elevated session is assumed):
$path = 'registry::HKEY_USERS\*\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Connections'
Remove-ItemProperty -WhatIf -Force -Path $path -Name DefaultConnectionSettings -ErrorAction SilentlyContinue
Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf once you're sure the operation will do what you want.

How to kill all programs running in folders and subfolders using PowerShell

I searched and found an icon, but it does not close programs that are running in subfolders.
I want to close programs running in subfolders
Note: You have to run the code in the folder you want, if anyone knows a way to add the file path instead of adding cd folder before the code, that would be fine.
This is the code
Get-Process | ?{$_.path -and (test-path (split-path $_.path -leaf ))} | Stop-Process -Force

How to use PowerShell to remove nonempty folder in OneDrive?

Descriptions
Cannot remove nonempty folder in OneDrive directory
Step to reproduce
Launch PowerShell in OneDrive directory
PS C:\Users\MyUserName\OneDrive>
Try to use Remove-Item cmdlet to remove a nonempty folder in this directory, for example: the .\test\ folder
PS C:\Users\MyUserName\OneDrive> Remove-Item .\test\
Expected result
Without the -Recurse parameter, PowerShell should return a confirm message, such as
Confirm
The item at C:\Users\MyUserName\OneDrive\test\ has children and the Recurse parameter was not specified. If you continue, all children will be removed with the item. Are you sure you want to continue?
[Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):
Actual result
PowerShell return a error message
Remove-Item: Cannot remove item C:\Users\MyUserName\OneDrive\test\: The directory is not empty. : 'C:\Users\MyUserName\OneDrive\test\'
Note
PowerShell and Administrator:PowerShell get the same result;
If I exit OneDrive process and create a new nonempty folder under OneDrive directory, PowerShell can remove it as normal (see Note 4., because unsynced folders do not have the ReparsePoint attribute);
CMD can remove the folder successfully, which means I can use the below command in PowerShell to remove the folder too. But I want to accomplish my goal just by PowerShell cmdlet;
cmd.exe /C "rd /s test"
Get-ChildItem cmdlet shows that the mode of normal folders (not synced by OneDrive) is 'd'(directory), but the mode of synced folders is 'l'(reparsepoint). Is this the reason that I cannot remove a folder under OneDrive directory as normal?
Version info
PSVersion:7.1.3
OS:Microsoft Windows 10.0.19042
OneDrive Version:21.052.0314.0001 (Office 365 A1)
Update
I try to remove the test folder on PowerShell 5 but fail, too.
The error message from PowerShell 5.1:
PS C:\Users\MyUserName\OneDrive> Remove-Item .\test\ -Force -Recurse
Remove-Item : Access to the cloud file is denied.
At line:1 char:1
+ rm .\test\ -Force -Recurse
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Remove-Item], Win32Exception
+ FullyQualifiedErrorId : System.ComponentModel.Win32Exception,Microsoft.PowerShell.Commands.RemoveItemCommand
I just hit the same thing and this worked for me:
Get-ChildItem -recurse .\test | Sort-Object -Property FullName -Descending | ForEach-Object { $_.Delete() }
(Get-Item test).Delete()
I'm rather new at PowerShell, so there might be more elegant or correct ways to do the above.
Previous answer did not handle hidden files,
You can add these to your profile
function rmc ($file) {
(Get-Item $file).Delete()
}
function rmd ($folder) {
Get-ChildItem -recurse -force $folder | Sort-Object -Property FullName -Descending | ForEach-Object { $_.Delete() }
(Get-Item $folder).Delete()
}
Onedrive folder's no different than any other folder in your system, the same folder removal PowerShell commands will be used. Here you go...
cd into the Onedrive folder.
Use, rm -r -fo <FolderName>

How to use -filter parameter in Powershell

I'm currently running a PowerShell (v3.0) script and I have some jpg files need tidy in a folder. I want to sort the files by the file creation date .but it doesn't work.
get-childitem -path $fipath\*.jpg|get-itemproperty -filter LastWritTime "2013/10/2"
the command get nothing besides err info.
I have tried many other methods but it doesn't work anymore how to use the parameter -filter in PowerShell anyone can gave a idea?
Try like this :
Get-ChildItem -path $fipath -filter *.jpg |where {$_.LastWriteTime.Date -eq "10/02/2013"}
date format should be like MM/DD/YYYY

How to associate icon with custom application(registered with a powershell script)

I use cygwin version of gvim to edit files in windows, for that I created a bat script that opens a file with cygwin version of gvim(by converting the path to cygwin format). I also wrote a small powershell script to register this bat script with windows explorer so I can associate file extensions using the 'open with' context menu. Here is the script:
$ErrorActionPreference = "Stop"
$classes="hkcu:\software\classes"
$appid="cygwin.gvim"
$apps="$classes\applications"
$cmd='...SOMEDIRECTORY...\edit-gvim.bat'
$friendlyname='gVim (Cygwin)'
$icon='...ANOTHERDIRECTORY...\vim.ico'
$filetypes=#(".txt", ".ps1", ".sh", ".py", ".cs", ".cpp", ".c", ".rb",
".zsh", ".bash", ".vbox", ".xml", ".yml", ".yaml", ".bat")
if (test-path "$apps\$appid") {
# cleanup
remove-item -recurse "$apps\$appid"
}
# register open commands to know filetypes
new-item -path "$apps\$appid\shell\open\command" -value "$cmd `"%1`"" -force
# add a context menu item(edit with gVim) to every file in windows explorer
new-item -path "$classes\*\shell\Edit with $friendlyname\command" -value "$cmd `"%1`"" -force
# friendly name for the 'open with' dialog
new-itemproperty -path "$apps\$appid\shell\open" -name 'FriendlyAppName' -value $friendlyname
# register the icon
# FIXME this has no effect
new-item -path "$apps\$appid\DefaultIcon" -value $icon -type expandstring
# register supported file extensions
new-item -path "$apps\$appid\SupportedTypes"
foreach ($ext in $filetypes) {
new-itemproperty -path "$apps\$appid\SupportedTypes" -name $ext -PropertyType string -value ''
}
Everything works except the line below the 'FIXME' comment, which aparently has no effect. Instead of seeing my provided icon with applications associated with gvim, I see windows default icon for unknown file types. What am I missing here?
Here are some resources I used to write this script:
http://msdn.microsoft.com/en-us/library/windows/desktop/ee872121(v=vs.85).aspx
http://msdn.microsoft.com/en-us/library/cc144158(VS.85).aspx
http://msdn.microsoft.com/en-us/library/windows/desktop/cc144101(v=vs.85).aspx
Create registry entry to associate file extension with application in C++
I can make a mistake, but as far as I understand the syntax of DefaultIcon is :
"Full path to a file,ordinal"
This is usefull when you want to point to a resource in an EXE or a DLL
C:\Program Files (x86)\PowerGUI\ScriptEditor.exe,1
But you have to keep the same syntax if you want to point to an icon file :
[HKEY_CLASSES_ROOT\AcroExch.acrobatsecuritysettings.1\DefaultIcon]
#="C:\\Windows\\Installer\\{AC76BA86-7AD7-1036-7B44-A95000000001}\\PDFFile_8.ico,0"
So, in your case, I would try :
$icon='...ANOTHERDIRECTORY...\vim.ico,0'
or
$icon='...ANOTHERDIRECTORY...\\vim.ico,0'
Edited
Don't forget to restart explroer.exe to see the new icon.

Resources