PowerShell set literalpath as parameter path - windows

Trying execute that command:
new-item -Path (Resolve-Path -LiteralPath "C:\Users\hittm\Downloads\openhardwaremonitor-v0.9.6\OpenHardwareMonitor\OpenHardwareMonitor.exe") -Name "OHW" -ItemType SymbolicLink
But getting error:
enter image description here
In Microsoft docs they said that path is already "LiteralPath" but it not work. If i truing execute string in path param all works fine.
UPD:
Problem is in wrong parameter here's correct code:
New-Item -Target 'C:\Users\hittm\Downloads\openhardwaremonitor-v0.9.6\OpenHardwareMonitor\OpenHardwareMonitor.exe' -Path .\OHW.lnk -ItemType SymbolicLink

Problem is in wrong parameter here's correct code:
New-Item -Target 'C:\Users\hittm\Downloads\openhardwaremonitor-v0.9.6\OpenHardwareMonitor\OpenHardwareMonitor.exe' -Path .\OHW.lnk -ItemType SymbolicLink
Parameter '-Path' in 'New-Item' command is parameter for result, for setting parameter to work with i need to use '-Target' instead

Related

Registry Powershell Output

I need your help
I need to print an logic condition in the specifc PowerShell output command.
Get-ItemProperty -Path 'HKLM:SOFTWARE\Policies\Microsoft\WindowsNT\TerminalServices' -Name fDisableCdm | Select fDisableCdm
I wrote a little script for test, but in my script I made a own conditional output. But I want print that what value have inside registry key and not print an own condition.
My script
if ($process=Get-ItemProperty -Path 'HKLM:SOFTWARE\Policies\Microsoft\WindowsNT\TerminalServices' -Name fDisableCdm -ErrorAction SilentlyContinue) {write-host "1"} else {write-host "0"}
You can help me ?
I waiting for help and tanks for all !
$regKey = "HKLM:SOFTWARE\Policies\Microsoft\WindowsNT\Terminal Services"
$regValue = 'fDisableCdm'
Try {
$process=Get-ItemProperty -Path $regKey -Name $regValue -ErrorAction Stop
Write-Output (-join($regValue,": ",$process.$regValue))
}
Catch {
Write-Output "There was an error: $($PSItem.ToString())"
}
You will need to check to see if your registry key for Terminal Services has a space or not. Mine has a space.
Otherwise, this script allows you to set the two variables at the beginning of the script, performs the requested lookup and, if no error occurs, outputs the requested information.
In the event of an error, the script outputs an appropriate error message.
Reference for meaningful error handling:
https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-exceptions?view=powershell-7.1

Checking for a file whether it is readable and regular in powershell

I'm new to powershell and I want to check if file in readable and regular. In unix we can do it in one line by using -f & -r. For example the following shell script function accepts filename as argument and checks the readability and regularity of file, whats the powershell equivalent for this?
_ChkRegularFile_R() # checks whether a file is regular and readable
{
_CRFRfilename=$1 # name of the file to be checked
_CRFRsts=1 # default is error
if [ -f "$_CRFRfilename" ]
then
if [ -r "$_CRFRfilename" ]
then
_CRFRsts=0 # success: regular file is readable
fi
fi
return $_CRFRsts
}
To test if a file is readable, you try to open it. If you get an error, then it's not readable. You need to either trap or catch exceptions or stop on errors, as appropriate. Remember, Windows locks files that are open for writing, so applications need to expect that they sometimes can't open a file.
If you absolutely have to, you can use something like this to test if you can read a file:
try {
[System.IO.File]::OpenRead($FullPathName).Close()
$Readable = $true
}
catch {
$Readable = $false
}
And this to test if you can write to a file:
try {
[System.IO.File]::OpenWrite($FullPathName).Close()
$Writable = $true
}
catch {
$Writable = $false
}
That logic is fairly easy to wrap into a function if you really need it.
As far as file types, nearly everything in the file system in Windows is a plain file or a directory, since Windows doesn't have the "everything is a file" convention. So, normally you can test as follows:
# Test if file-like
Test-Path -Path $Path -Leaf
# Test if directory-like
Test-Path -Path $Path -Container
If you're working with a FileInfo or DirectoryInfo object (i.e., the output of Get-Item, Get-ChildItem, or a similar object representing a file or directory) you'll have the PSIsContainer property which will tell you if the item is a file or a directory.
That covers probably 99.999% of cases.
However, if you need to know if something is an NTFS hard link to a file (rare, but oldest), an NTFS junction to a directory, an NTFS symlink, an NTFS volume mount point, or any type of NTFS reparse point, it gets much more complicated. [This answer does a good job describing the first three.]
Let's create a simple NTFS folder to test with:
# Create a test directory and change to it.
New-Item -Path C:\linktest -ItemType Directory | Select-Object -ExpandProperty FullName | Push-Location
# Create an empty file
New-Item -Path .\file1 -ItemType file -Value $null | Out-Null
New-Item -Path .\file2 -ItemType file -Value $null | Out-Null
# Create a directory
New-Item -Path .\dir1 -ItemType Directory | Out-Null
# Create a symlink to the file
New-Item -ItemType SymbolicLink -Path .\sfile1 -Value .\file1 | Out-Null
# Create a symlink to the folder
New-Item -ItemType SymbolicLink -Path .\sdir1 -Value .\dir1 | Out-Null
# Create a hard link to the file
New-Item -ItemType HardLink -Path .\hfile1 -Value .\file1 | Out-Null
# Create a junction to the folder
New-Item -ItemType Junction -Path .\jdir1 -Value .\dir1 | Out-Null
# View the item properties
Get-ChildItem -Path . | Sort-Object Name | Format-Table -Property Name, PSIsContainer, LinkType, Target, Attributes -AutoSize
Your output will be:
Name PSIsContainer LinkType Target Attributes
---- ------------- -------- ------ ----------
dir1 True {} Directory
file1 False HardLink {C:\linktest\hfile1} Archive
file2 False {} Archive
hfile1 False HardLink {C:\linktest\file1} Archive
jdir1 True Junction {C:\linktest\dir1} Directory, ReparsePoint
sdir1 True SymbolicLink {C:\linktest\dir1} Directory, ReparsePoint
sfile1 False SymbolicLink {C:\linktest\file1} Archive, ReparsePoint
Note that both file1 and hfile1 are hard links, even though file1 wasn't created as such.
To clean up the above garbage, do:
Get-ChildItem -Path C:\linktest\ | ForEach-Object { $_.Delete() }
There's a bug in Remove-Item with deleting some container links which prevents the command from removing the items.
The general solution would be to get the item and test it:
# Get the item. Don't use Get-ChildItem because that will get a directory's contents
$Item = Get-Item -Path $Path
# Is it a container
$Item.PSIsContainer
# Is it a link of some kind?
[System.String]::IsNullOrWhiteSpace($Item.LinkType)
$Item.LinkType -eq 'Junction'
# Is it a Reparse Point?
($Item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) -eq [System.IO.FileAttributes]::ReparsePoint
There are several other potential attributes, too:
PS> [System.Enum]::GetNames([System.IO.FileAttributes])
ReadOnly
Hidden
System
Directory
Archive
Device
Normal
Temporary
SparseFile
ReparsePoint
Compressed
Offline
NotContentIndexed
Encrypted
IntegrityStream
NoScrubData
Note that Device is documented as reserved for future use. Ain't no device file type in Windows.
For volume mount points, I'm not 100% sure how those look. I know you can create them on Windows 8.1 and later with Get-Partition followed by an appropriate Add-PartitionAccessPath, but I'm on Windows 7 currently. I'm afraid I have no means of testing this at the moment.
Finally, I have no idea how exactly PowerShell Core 6.0 on Linux handles file types.
Soooo,,,,
This is not something I regulary do, but if memory serves. In *nix, a regular file contains data, is a direcotry,
Again, not somehting I do/have to worry about under normal PoSH stuff.
So you are testing for where the object is a writable file (and / or non-zero) or a directory or binary?
So, in PoSH, prior to v3... you do something like this...
$IsDir = {$_.PsIsContainer}
$IsFile = {!$_.PsIsContainer}
ls D:\Temp | Where $IsDir
lsectory: D:\Temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 1/4/2018 2:31 PM ArchiveDestination
d----- 1/4/2018 1:40 PM ArchiveSource
d----- 1/1/2018 3:34 PM diff
...
ls D:\Temp | Where $IsFile
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 6/7/2017 5:28 PM 512 CombinedSources07Jun2017.txt
-a---- 2/24/2018 6:29 PM 115 EmpData.csv
-a---- 11/18/2017 6:47 PM 11686 fsoVolume.docx
...
PoSH V3 and higher. This is supported natively e.g.:
ls -directory
ls -ad
ls -file
ls -af
Of course any of the above can be set to just return true or false using if/then or try/catch.
If all the above is a bit more typing than you'd like then you can create your own function and give it whatever alias you choose, well, as long as it's not an alias already in use.
See the help files ...
# Get parameters, examples, full and Online help for a cmdlet or function
(Get-Command -Name Get-ChildItem).Parameters
Get-help -Name Get-ChildItem -Examples
Get-help -Name Get-ChildItem -Full
Get-help -Name Get-ChildItem -Online
Get-Help about_*
Get-Help about_Functions
Get-Alias -Definition Get-ChildItem
# Find all cmdlets / functions with a target parameter
Get-Help * -Parameter Append
# All Help topics locations
explorer "$pshome\$($Host.CurrentCulture.Name)"
Of course you can check / modify file attributes as well. See this article on the topic:
File Attributes in PowerShell
Fun with file and folder attributes, via PowerShell and the DIR command.
https://mcpmag.com/articles/2012/03/20/powershell-dir-command-tricks.aspx
So, you could do something like this, to achieve the same attribute check
Get-ChildItem -Path $FilePath -File -Force | Where {$_.Attributes -notmatch 'ReadOnly'}
Or a function wiht an alias.
Function Test-RegularFile
{
[CmdletBinding()]
[Alias('trf')]
Param
(
[string]$FilePath
)
try
{
Get-ChildItem -Path $FilePath -File -Force `
| Where {$_.Attributes -notmatch 'ReadOnly'}
"$FilePath is a regular file" # success: regular file is readable
}
catch
{
Write-Warning -Message "$FilePath is not a Regular file."
}
}
trf -FilePath D:\Temp\fsoVolume.txt
Since you are new to PoSH, it reall important / vital that you get a base understanding before looking at conversion comparisons.
See this post for folks providing some paths for learning PowerShell.
https://www.reddit.com/r/PowerShell/comments/7oir35/help_with_teaching_others_powershell
To test whether it's a regular file:
Test-Path -PathType Leaf foo.txt
To test whether it's readable:
Get-ChildItem foo.txt | ? { $_.Mode -match 'r'}
To test whether it's hidden:
Get-ChildItem -force foo.txt | ? { $_.Mode -match 'h'}

Copy-Item : The given path's format is not supported

I am trying to copy configuration files for an Active X controller to all user profiles on remote computers and I am running into problems. I have tried several variations of the code to no avail, my most recent, simplified code is shown below which is generating a path format not supported error:
$From = "C:\Interactive" $To = "C:\Users\$user\appdata\Microsoft\Internet Explorer\Downloaded Program Files" ForEach ($user in (Get-ChildItem C:\Users -Exclude Public)){Copy-Item -Path $From -Destination $To}
I assume there is an argument I am missing or some sort of syntax but I cannot find it. I plan on deploying this script using PS App Deploy Toolkit through SCCM when it is working (Group Policy is not currently a viable solution for me at this time)
I have spent my day trying to find a working script and I have come up empty. I used to use Set-ActiveSetup Stub ExePath but that seems to not be working any longer.
Well I found a way that works for me. I am including how I went about it, ignore the part with the DLL registration-
$Source = "C:\Temp\Downloaded Program Files"
$Destination = "C:\users\*"
$Items = Get-ChildItem -Path $Destination
foreach ($Item in $Items)
{
Write-Verbose "List of folders: $item" -Verbose ##added for visibility when I was testing
Copy-Item $Source -Destination "$item\AppData\Local\Microsoft\Internet Explorer" -Force -Recurse
$CKIDLL = "`"$item\Appdata\Local\Microsoft\Internet Explorer\Downloaded Program Files\CKInteractiveDriver.dll`""
Start-Process -Filepath 'regsvr32.exe' -Args "/s $CKIDLL"
}

Powershell Set-ItemProperty: How does one pass a variable to the -value parameter?

Greetings and happy holidays!
I hope this question hasn't been answered somewhere else, because I've searched Stack and Google for about an hour now and haven't yet seen examples or posts that answer exactly what I'm trying to accomplish.
I created a script that checks the WindowsUpdate and WindowsUpdate\AU registry keys and the associated values for correct data configuration. If they are inconsistent with the desired configuration, it corrects them. I'm at home, so the script below isn't exactly how I created it at the job (I obtained my registry keys / values differently), but should give you a general idea of what I'm looking to do:
param($comp, [string]$location)
switch($location)
{
"EAST" {$WUServerDesConfig = "https://myeastmp.domain.com:8531"}
"WEST" {$WUServerDesConfig = "https://mywestmp.domain.com:8531"}
}
$WUServerActual = Invoke-Command -ComputerName $comp -scriptblock {(Get-ItemProperty -Path HKLM:\\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate).WUServer}
if($WUServerActual -ne $WUServerDesConfig)
{
Invoke-Command -ComputerName $comp -ScriptBlock {Set-ItemProperty -Path HKLM:\\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate -Name WUServer -Type String -Value $WUServerDesConfig}
}
This doesn't work, and it seems that the reason behind it is that you can't pass an ordinary variable to the -value parameter for Set-ItemProperty (I believe it takes an object). Why this is, I have absolutely no idea, because if I just replace the variable with the string itself, it works without incident. The problem with this approach, however, is that, depending upon region, the server changes.
I consider myself to have only intermediate knowledge of PowerShell thus far (getting better every day though, I swear), so any assistance or suggestions on how to best accomplish this would be appreciated. Thanks!
This is an issue that most people run into when they start using invoke-command.
The most common solution is to pass the values you want in and use the $args variable like this:
Invoke-Command -ComputerName $comp -ArgumentList $WUServerDesConfig -ScriptBlock {
Set-ItemProperty -Path HKLM:\\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate -Name WUServer -Type String -Value $args[0]
}
Another common solution is to add a param block like this:
Invoke-Command -ComputerName $comp -ArgumentList $WUServerDesConfig -ScriptBlock {
param($param1)
Set-ItemProperty -Path HKLM:\\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate -Name WUServer -Type String -Value $param1
}
But there is a solution that uses scope rules that feels like a much better fit most of the time. There is a $using: scope that will give you access to your variable inside a script block like this.
Invoke-Command -ComputerName $comp -ScriptBlock {
Set-ItemProperty -Path HKLM:\\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate -Name WUServer -Type String -Value $Using:WUServerDesConfig
}
I took the time to point out the other methods to help anyone else that has this issue.
Use the -ArgumentList parameter to pass local variables to the script block:
Invoke-Command -ComputerName $comp -ScriptBlock {Set-ItemProperty -Path HKLM:\\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate -Name WUServer -Type String -Value $args[0] } -ArgumentList $WUServerDesConfig

search for a folder buried in a folder and move the folder to a new destination

I want to move the Favorites folder from a folder that changes its folder guid daily from Appsense.
Text between quotes changes.
C:\appsensevirtual\S-1-5-21-220523388-2000478354-839522115-60875\'{647CFC75-E4C0-4F13-9888-C37BA083416C}'\_Microsoft Office 2010
I have found this but it never copies to the H: (Homedrive).
Get-ChildItem "C:\Appsensevirtual" -Recurse -Filter "Favorites*" -Directory |
Move-Item -Destination "H:\Favorites"
If i run I get this in an Powershell Administrator Window (powershell 2)
PS C:\temp> .\favorites.ps1
Get-ChildItem : A parameter cannot be found that matches parameter name 'Directory'.
At C:\temp\favorites.ps1:1 char:76
+ Get-ChildItem "C:\Appsensevirtual" -Recurse -Filter "Favorites*" -Directory <<<< | Move-Item -Destination "H:\Favorites"
+ CategoryInfo : InvalidArgument: (:) [Get-ChildItem], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
You solution is:
Remove -Directory from your command, and add -Force which will parse system & hidden folders.
Get-ChildItem "C:\Appsensevirtual" -Recurse -Filter "Favorites*" -Force |
Move-Item -Destination "H:\Favorites"

Resources