Common PowerShell Commands

Recently, WebShell needed to support file management under PowerShell. To perform file-related operations, it’s necessary to understand the relevant commands. Here’s the summary.

https://static.1991421.cn/2024/2024-03-31-114718.jpeg

Compress Folder

1
Compress-Archive -Path '${formatted}' -DestinationPath '${zipTempPath}'

Copy File/Folder

1
Copy-Item -Path '${filePath}' -Destination '${dirPath}' -Recurse -Force

Move File/Folder

1
Move-Item -Path '${filePath}' -Destination '${targetPath}' -Force

Extract ZIP Archive

1
Expand-Archive -Path '${path}.zip' -DestinationPath '${destinationPath}';Remove-Item -Path '${path}.zip' -Force

Delete File/Folder

1
Remove-Item -Path '${formatted}' -Recurse -Force

Create Folder

1
New-Item -Path '${formatted}' -ItemType Directory

Rename

1
Rename-Item -Path '${formatted}' -NewName '${newName}'

Multiple Command Execution

If need to execute multiple commands, unlike using && in Linux, PowerShell requires ;.

1
Move-Item -Path '${path}' -Destination '${path}.zip';Expand-Archive -Path '${path}.zip' -DestinationPath '${destinationPath}';Remove-Item -Path '${path}.zip' -Force

Common Issues

w2: Cannot load file C:\Program Files\node js\w2.ps1 because running scripts is disabled on this system.

1
2
3
4
5
6
# Run PowerShell as administrator

# Check the current PowerShell script execution policy
get-ExecutionPolicy
# Set PowerShell's execution policy to RemoteSigned
set-executionpolicy remotesigned

Path Contains []

If the path contains [], for example, executing Move-Item doesn’t throw an error but the execution is unsuccessful. The reason is that [] in the path is treated as regex, regardless of whether it’s a single or double quote. There are two solutions:

  1. Escape []

    For example:

    1
    Move-Item -Path 'C:\\Windows\\Temp\\`[漫威`] xxx.jar_1717312576427' -Destination 'C:\\Windows\\system32\\config\\systemprofile\\`[漫威`] xxx.jar' -Force
  2. Change -Path to -LiteralPath

    1
    Move-Item -LiteralPath 'C:\\Windows\\system32\\config\\systemprofile\\123 456\\[漫威] xxx.jar' -Destination 'C:\\Windows\\system32\\config\\systemprofile\\789\\[漫威] xxx.jar' -Force

Write at the End

When executing Windows commands, you can choose between PowerShell and CMD. According to Microsoft’s recommendation, using PowerShell is advised, as CMD has entered the maintenance phase.

Documentation