Does verb 'pintohome' be fully disable since later version of win10?

Steins 41 Reputation points
2024-11-14T12:04:01.5066667+00:00

I have a powershell script helps to pin some folder to Frequent Folder to quickly achieve them. It used to work well on win10.

But recently i found it that the script will be fully stucked unless i kill the window or thread, but its still ok the do it with context menu manually.

So i'm wondering is this true that since a specific version of windows, we will not able to use pintohome` or `` `unpinfromhome ``` in powershell script?

Here's my latest script

p
$job = Start-Job -ScriptBlock {
    $o = new-object -com shell.application
    $o.Namespace('c:\My Folder').Self.InvokeVerb("pintohome")
}

if (Wait-Job -Job $job -Timeout 3) {
    Write-Output "The folder has been pinned successfully."
} else {
    Stop-Job -Job $job
    Write-Error "The operation took too long to run and has been stopped."
}

Remove-Job -Job $job
p
Windows 10
Windows 10
A Microsoft operating system that runs on personal computers and tablets.
12,007 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,759 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. S.Sengupta 21,656 Reputation points MVP
    2024-11-21T00:36:34.06+00:00

    This issue is related to the changes in the shell APIs in recent versions of Windows, particularly in Windows 11 and later versions of Windows 10.

    What I understand is that Microsoft has been progressively restricting direct shell manipulation, likely due to security and performance concerns. This means that some of the older PowerShell pinning methods may no longer work as expected or may become unreliable.

    You can try using the registry to perform the pinning operation. This method may be more reliable than the direct shell interaction.


  2. Steins 41 Reputation points
    2025-01-24T13:10:31.2433333+00:00

    In a newly installed system, whether its win10 or win11, the script works well.

    After some trying, i believe its mainly because of some app changes some related registry, because when i uninstalled some app, the problem gone, and sadly, i was not aware of which may cause the problem and had not keep a backup of my registry.

    I did write a python script try to find which registry is the cause, if you have the same problem, maybe consider using it to find the answer, and dont forget to let me know it.

    import winreg
    import os
    import subprocess
    from typing import Dict, Tuple, List
    import logging
    from datetime import datetime
    
    def setup_logging():
        """Setup logging configuration"""
        log_file = f'reg_restore_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log'
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s',
            handlers=[
                logging.FileHandler(log_file, encoding='utf-8'),
                logging.StreamHandler()
            ]
        )
        logging.info('Starting registry restoration program')
    
    def parse_reg_file(file_path: str) -> Dict[str, Dict[str, str]]:
        """Parse reg file and return registry data in dictionary format"""
        logging.info(f'Starting to parse registry file: {file_path}')
        reg_data = {}
        current_key = ""
        
        try:
            with open(file_path, 'r', encoding='utf-16') as f:
                for line_num, line in enumerate(f, 1):
                    line = line.strip()
                    if line.startswith('['):
                        current_key = line[1:-1]
                        reg_data[current_key] = {}
                        logging.debug(f'Found registry key: {current_key}')
                    elif '=' in line:
                        name, value = line.split('=', 1)
                        reg_data[current_key][name] = value
                        logging.debug(f'Key-value pair: {name} = {value}')
        except Exception as e:
            logging.error(f'Error parsing file {file_path}: {str(e)}')
            raise
        
        logging.info(f'Successfully parsed file {file_path}, contains {len(reg_data)} keys')
        return reg_data
    
    def compare_reg_files(prod_data: Dict, dev_data: Dict) -> List[Tuple[str, str, str, str]]:
        """Compare differences between two registry files"""
        logging.info('Starting to compare registry file differences')
        differences = []
        
        for key in prod_data:
            if key not in dev_data:
                logging.info(f'Found new key: {key}')
                for name, value in prod_data[key].items():
                    differences.append((key, name, value, 'add_key'))
                    logging.debug(f'Need to add: {key}\\{name} = {value}')
            else:
                for name, value in prod_data[key].items():
                    if name not in dev_data[key] or dev_data[key][name] != value:
                        differences.append((key, name, value, 'update_value'))
                        logging.info(f'Found different value: {key}\\{name}')
                        logging.debug(f'prod value: {value}')
                        logging.debug(f'dev value: {dev_data[key].get(name, "does not exist")}')
        
        logging.info(f'Comparison completed, found {len(differences)} differences')
        return differences
    
    def apply_reg_entry(key: str, name: str, value: str, action: str) -> bool:
        """Apply single registry entry"""
        logging.info(f'Applying registry entry: {key}\\{name}')
        temp_reg_file = 'temp.reg'
        
        try:
            with open(temp_reg_file, 'w', encoding='utf-16') as f:
                f.write('Windows Registry Editor Version 5.00\n\n')
                f.write(f'[{key}]\n')
                f.write(f'"{name}"={value}\n')
            
            logging.debug(f'Temporary reg file created: {temp_reg_file}')
            subprocess.run(['regedit', '/s', temp_reg_file], check=True)
            logging.info('Registry entry applied successfully')
            os.remove(temp_reg_file)
            return True
        except subprocess.CalledProcessError as e:
            logging.error(f'Failed to apply registry entry: {str(e)}')
            if os.path.exists(temp_reg_file):
                os.remove(temp_reg_file)
            return False
        except Exception as e:
            logging.error(f'Unexpected error occurred: {str(e)}')
            if os.path.exists(temp_reg_file):
                os.remove(temp_reg_file)
            return False
    
    def verify_reg_entry(key: str, name: str, value: str) -> bool:
        """Verify if registry entry is correctly applied
        Implementation of verification logic needed based on specific requirements
        """
        # TODO: Implement specific verification logic
        return True
    
    def save_failed_entry(key: str, name: str, value: str, output_file: str):
        """Save failed registry entries to new reg file"""
        logging.info(f'Saving failed registry entry to file: {output_file}')
        try:
            with open(output_file, 'a', encoding='utf-16') as f:
                if f.tell() == 0:
                    f.write('Windows Registry Editor Version 5.00\n\n')
                f.write(f'[{key}]\n')
                f.write(f'"{name}"={value}\n\n')
            logging.info('Save successful')
        except Exception as e:
            logging.error(f'Error while saving failed entry: {str(e)}')
    
    def main():
        setup_logging()
        logging.info('='*50)
        logging.info('Program execution started')
        
        try:
            # Check if files exist
            for file in ['prod.reg', 'dev.reg']:
                if not os.path.exists(file):
                    logging.error(f'File not found: {file}')
                    return
            
            # Read registry files
            logging.info('Starting to read registry files')
            prod_data = parse_reg_file('prod.reg')
            dev_data = parse_reg_file('dev.reg')
            
            # Compare differences
            differences = compare_reg_files(prod_data, dev_data)
            
            # Process each different registry entry
            failed_reg_file = 'failed_entries.reg'
            if os.path.exists(failed_reg_file):
                logging.info(f'Deleting existing failed entries file: {failed_reg_file}')
                os.remove(failed_reg_file)
            
            total = len(differences)
            success = 0
            failed = 0
            
            for i, (key, name, value, action) in enumerate(differences, 1):
                logging.info(f'Processing entry {i}/{total}')
                if apply_reg_entry(key, name, value, action):
                    if verify_reg_entry(key, name, value):
                        success += 1
                        logging.info('Verification successful')
                    else:
                        failed += 1
                        logging.warning('Verification failed')
                        save_failed_entry(key, name, value, failed_reg_file)
                else:
                    failed += 1
                    save_failed_entry(key, name, value, failed_reg_file)
            
            logging.info('='*50)
            logging.info(f'Execution completed: Total {total} entries, {success} successful, {failed} failed')
            if failed > 0:
                logging.info(f'Failed entries saved to: {failed_reg_file}')
                
        except Exception as e:
            logging.error(f'Error occurred during program execution: {str(e)}')
            raise
    
    if __name__ == '__main__':
        main()
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.