PowerShell PSCX Read-Archive: Cannot bind parameter... problem - powershell-2.0

I'm running across a problem I can't seem to wrap my head around using the Read-Archive cmdlet available via PowerShell Community Extensions (v2.0.3782.38614).
Here is a cut down sample used to exhibit the problem I'm running into:
$mainPath = "p:\temp"
$dest = Join-Path $mainPath "ps\CenCodes.zip"
Read-Archive -Path $dest -Format zip
Running the above produces the following error:
Read-Archive : Cannot bind parameter 'Path'. Cannot convert the "p:\temp\ps\CenCodes.zip" value of type "System.String" to type "Pscx.IO.PscxPathInfo".
At line:3 char:19
+ Read-Archive -Path <<<< $dest -Format zip
+ CategoryInfo : InvalidArgument: (:) [Read-Archive], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Pscx.Commands.IO.Compression.ReadArchiveCommand
If I do not use Join-Path to build the path passed to Read-Archive it works, as in this example:
$mainPath = "p:\temp"
$path = $mainPath + "\ps\CenCodes.zip"
Read-Archive -Path $path -Format zip
Output from above:
ZIP Folder: CenCodes.zip#\
Index LastWriteTime Size Ratio Name ----- ------------- ---- ----- ----
0 6/17/2010 2:03 AM 3009106 24.53 % CenCodes.xls
Even more confusing is if I compare the two variables passed as the Path argument in the two Read-Archive samples above, they seem identical:
This...
Write-Host "dest=$dest"
Write-Host "path=$path"
Write-Host ("path -eq dest is " + ($dest -eq $path).ToString())
Outputs...
dest=p:\temp\ps\CenCodes.zip
path=p:\temp\ps\CenCodes.zip
path -eq dest is True
Anyone have any ideas as to why the first sample gripes but the second one works fine?

I created an item in the issue tracker on the CodePlex home of PSCX. Apparently this is a current known issue with PscxPathInfo. (See item #28023 in the PSCX Issue Tracker).
A work around is to do this:
Get-Item $dest | Read-Archive
Credit to r_keith_hill on CodePlex for that particular work around.

Related

Search in/for text in files

I am currently learning LPTHW Ex 46. In his video tutorial, Zed had done the following commands:
Find NAME within files using grep -r "NAME" *.
Find all files with extension ending in .pyc using find . -name "*pyc" -print.
Unfortunately, the above code does not work on Windows PowerShell. May I know what their Windows PowerShell equivalents are?
Based on my search, item 1 can be replaced by Select-String. However, it is not as good as we can only search specific files and not directories. For example, while this would work:
Select-String C:\Users\KMF\Exercises\Projects\gesso\gesso\acrylic.py -pattern "NAME"
this would not:
Select-String C:\Users\KMF\Exercises\Projects\gesso -Pattern "NAME"
and it gives the following error
Select-String : The file C:\Users\KMF\Exercises\Projects\gesso can not be read: Access to the path 'C:\Users\KMF\Exercises\Projects\gesso' is denied.
For item 2 I could not find a similar function.
grep and find are Unix/Linux shell commands. They won't work in PowerShell unless you install a Windows port of them.
As you already found out, Select-String is the PowerShell equivalent for grep. It doesn't recurse by itself, though, so you have to combine it with Get-ChildItem to emulate grep -r:
Get-ChildItem -Recurse | Select-String -Pattern 'NAME'
For emulating find you'd combine Get-ChildItem with a Where-Object filter:
Get-ChildItem -Recurse | Where-Object { $_.Extension -eq '.pyc' }
PowerShell cmdlets can be aliased to help administrators avoid extensive typing (since PowerShell statements tend to be rather verbose). There are several built-in aliases, e.g. ls or dir for Get-ChildItem, and ? or where for Where-Object. You can also define aliases of your own, e.g. New-Alias -Name grep -Value Select-String. Parameter names can be shortened as long as the truncated parameter name remains unique for the cmdlet. When cmdlets allow positional parameters they can even be omitted entirely.
With all of the above your two PowerShell statements can be reduced to the following:
ls -r | grep 'NAME'
ls -r | ? { $_.Extension -eq '.pyc' }
Note however, that aliases and abbreviations are mainly intended as an enhancement for console use. For PowerShell scripts you should always use the full form, not only for readability, but also because aliases may differ from environment to environment. You don't want your scripts to break just because they're run by someone else.

Can't replace file names with PowerShell 2.0

I have files like this.
[mix]aaaa.flv
[mix]aaaa.mpv
[mix]aaaa.ogv
[mix]aaaa.webm
[mix]bb.flv
[mix]bb.mpv
[mix]bb.ogv
[mix]bb.webm
...
I just need to remove "[mix]" from the file names.
I use this command, but failed
Dir | Rename-Item –NewName { $_.name –replace "[mix]", "" }
Error says
Rename-Item : 'Microsoft.PowerShell.Core\FileSystem::C:\Users\Desktop\[mix]aaaa.mp4'에 항목이 없으므로 이름을 바꿀 수 없습니다.
위치 줄:1 문자:18
+ Dir | Rename-Item <<<< –NewName { $_.name –replace “[mix]“,”” }
+ CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
There's korean in error code, it might say : Can't change name, there is no item at 'Microsoft.PowerShell.Core\FileSystem::C:\Users\Desktop\[mix]aaaa.mp4'
And I don't understand what I'm doing wrong. I used to change file names with this command.
I think this is a known bug with Rename-Item and powershell 2.0
What I did was to use Move-Item instead, you should be able to use the following (tested on powershell 2.0):
Dir | Move-Item -Destination {$_.Name -replace "\[mix\]", ""}
I was able to make this work. Remember that [ and ] are regex metacharacters and need to be escaped:
Dir | Rename-Item -NewName {$_.Name -replace "\[mix\]",""}

How to select all files of a given filetype EXCEPT ones matching a name pattern?

I'm trying to select all files of a certain type in a given directory EXCEPT ones beginning with certain names. Why didn't this code work?
PS C:\Documents and Settings\wdennis> Get-Item -Path ($AppDir + "reports\*.dbf") | Where-Object {$_.Name -ne "reports*" -or "category*"}
Directory: C:\Program Files\Application\reports
Mode LastWriteTime Length Name
---- ------------- ------ ----
----- 1/4/2007 9:37 AM 4842 category.dbf
----- 9/7/2007 1:53 PM 43903 reports.dbf
I'm pretty new to PS, and very tired to boot, so maybe that's why I'm not understanding why this didn't work. How to do this?
I think that -eq and -ne match the given string and don't support wildcards.
Only -like supports wildcards for pattern matching.
You can however use a regular expression with the -notmatch switch to achieve what you want. Since it's a regular expression now you need to use .* instead of *. And the beginning is marked with ^.
So you end with this
{$_.Name -notmatch "^reports.*|^category.*"}
The whole command
Get-Item -Path ($AppDir + "reports\*.dbf") | Where-Object {$_.Name -notmatch "^reports.*|^category.*"}

Unable to collect *.bak files as a single object

I am new to PowerShell.
I wanted to write a simple program to list all *.bak files which I can then either sort by date or size as shown below.
$Drives = Get-WMIObject -class win32_logicaldisk -filter "DriveType = 3" ;
foreach ($d in $Drives){
If (($d.deviceId -ne "C:") -and ($d.VolumeName -ne "PAGEFILE")) {
$backups += Get-ChildItem -Path $d.deviceID -Recurse -filter *.bak
}
This generally works fine except when say for example D: drive has only one *.bak file.
In that case I get an error.
Method invocation failed because [System.IO.FileInfo] doesn't contain a method named 'op_Addition'.
At F:\work\PowerShell\DiskSpace\generate-disk-report-v2.ps1:39 char:13
+ $backups += <<<< Get-ChildItem -Path $d.deviceID -Recurse -filter *.bak
+ CategoryInfo : InvalidOperation: (op_Addition:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
If I add an additional junk.bak to that drive, it works fine.
In my case, I found that the variable needs to be initialized as an array and Get-ChildItem needs to be returned as an array even, or especially, if it's only returning one file.
In your case:
$backups = #() - (Before calling Get-ChildItem)
and
$backups = #(Get-ChildItem -Path $d.deviceID -Recurse -filter *.bak) - (Cast as an array)

Powershell: Count items in a folder with PowerShell

I'm trying to write a very simple PowerShell script to give me the total number of items (both files and folders) in a given folder (c:\MyFolder). Here's what I've done:
Write-Host ( Get-ChildItem c:\MyFolder ).Count;
The problem is, that if I have 1 or 0 items, the command does not work---it returns nothing.
Any ideas?
You should use Measure-Object to count things. In this case it would look like:
Write-Host ( Get-ChildItem c:\MyFolder | Measure-Object ).Count;
or if that's too long
Write-Host ( dir c:\MyFolder | measure).Count;
and in PowerShell 4.0 use the measure alias instead of mo
Write-Host (dir c:\MyFolder | measure).Count;
I finally found this link:
https://blogs.perficient.com/microsoft/2011/06/powershell-count-property-returns-nothing/
Well, it turns out that this is a quirk caused precisely because there
was only one file in the directory. Some searching revealed that in
this case, PowerShell returns a scalar object instead of an array.
This object doesn’t have a count property, so there isn’t anything to
retrieve.
The solution -- force PowerShell to return an array with the # symbol:
Write-Host #( Get-ChildItem c:\MyFolder ).Count;
If you need to speed up the process (for example counting 30k or more files) then I would go with something like this..
$filepath = "c:\MyFolder"
$filetype = "*.txt"
$file_count = [System.IO.Directory]::GetFiles("$filepath", "$filetype").Count
Only Files
Get-ChildItem D:\ -Recurse -File | Measure-Object | %{$_.Count}
Only Folders
Get-ChildItem D:\ -Recurse -Directory | Measure-Object | %{$_.Count}
Both
Get-ChildItem D:\ -Recurse | Measure-Object | %{$_.Count}
You can also use an alias
(ls).Count
Recursively count files in directories in PowerShell 2.0
ls -rec | ? {$_.mode -match 'd'} | select FullName, #{N='Count';E={(ls $_.FullName | measure).Count}}
In powershell you can to use severals commands, for looking for this commands digit: Get-Alias;
So the cammands the can to use are:
write-host (ls MydirectoryName).Count
or
write-host (dir MydirectoryName).Count
or
write-host (Get-ChildrenItem MydirectoryName).Count
To count the number of a specific filetype in a folder.
The example is to count mp3 files on F: drive.
( Get-ChildItme F: -Filter *.mp3 - Recurse | measure ).Count
Tested in 6.2.3, but should work >4.

Resources