Instead of typing PsIsContainer, I would like to be able to use either "dir" or "folder" strings. Is there a way in PowerShell that allows me to substitute one string for another, as in this case?
2 Answers
I think you could get close to what you're afer by predefining a couple of scriptblocks e.g.:
$IsDir = {$_.PsIsContainer}
$IsFile = {!$_.PsIsContainer}
dir | Where $IsDir
dir | Where $IsFile
Good news in PowerShell V3. This is supported natively e.g.:
dir -directory
dir -ad
dir -file
dir -af
-
i like the *nix functions like dird: function dird { dir | ? { $_.psiscontainer} }– x0nJan 26, 2012 at 3:36
You could update your TypeData for the System.IO.FileInfo
type using the following file and the Update-TypeData
cmdlet.
D:\fileinfo.ps1xml
<?xml version="1.0" encoding="utf-8" ?>
<Types>
<Type>
<Name>System.IO.FileSystemInfo</Name>
<Members>
<ScriptProperty>
<Name>dir</Name>
<GetScriptBlock>
$this.psiscontainer
</GetScriptBlock>
</ScriptProperty>
<ScriptProperty>
<Name>file</Name>
<GetScriptBlock>
! ($this.psiscontainer)
</GetScriptBlock>
</ScriptProperty>
</Members>
</Type>
</Types>
Update the TypeData:
update-typedata D:\fileinfo.ps1xml
Now you will be able to type:
gci | ?{$_.dir}
and
gci | ?{$_.file}