I'm interested in adding a property to my files under a certain scope that contains their current locations in my file system, in order to track file movement. I would think that this could be done with New-ItemProperty, with a command similar to the following:
Get-ChildItem -recurse | foreach { New-ItemProperty -Path $.FullName -Name "OriginalLocation" -PropertyType string -Value $.FullName }
However, when I try this, I'm spammed with the following error:
New-ItemProperty : Cannot use interface. The IDynamicPropertyCmdletProvider interface is not implemented by this provider.
After some searching, it appears that New-ItemProperty is all but useless except for working with the registry. Fine. Windows has myriad other file properties I should be able to hijack in order to get this done. "Label" and "Tags" come to mind. So let's try setting those via Set-ItemProperty instead.
Set-ItemProperty : Property System.String Label=D:\test\file.txt does not exist.
It appears I need to create these properties after all. Is this a shortcoming of New-ItemProperty? Maybe setting properties such as this on arbitrary items is some WMI thing I don't know about?
Here is my solution using the redirections ('<' & '>') that allow to manipulate alternate data stream in CMD.EXE. It works in Powershell without any extentions
# AlternateDataStream.ps1
$scriptBlockSetStream = {cmd /C `"echo $($Args[0])`>$($Args[1]):$($Args[2])`"}
$scriptBlockGetStream = {cmd /C `"more `<$($Args[0]):$($Args[1])`"}
$streamName = "NativeFilePath"
$File = "C:\Temp\ADSTest\toto.txt"
$streamContent = Split-Path -Path $File -Parent
# Set the data stream
Invoke-Command -ScriptBlock $scriptBlockSetStream -ArgumentList $streamContent,$File,$streamName
# Get the Data Stream
$res = Invoke-Command -ScriptBlock $scriptBlockGetStream -ArgumentList $File,$streamName
$res
Another option might be to use alternate data streams to store your path. If you are running PowerShell 3.0, you can manipulate them quite easily. Based on the first article, you would have something resembling:
"echo test" | out-file c:\powershell\test.ps1
$fs = new NTFS.FileStreams('c:\powershell\test.ps1')
$fs.add('OriginalPath')
$stream = $fs.Item('OriginalPath').open()
$sw = [System.IO.streamwriter]$stream
$sw.writeline('<path>')
$sw.close()
$stream.close()
Related
I want a powershell script to run each time a user login to Windows by placed in: Shell:common startup.
This script must add about 50 Regkey's in HKCU, which is setting/path for Presetfolders for a application.
I want to use Powershell and have tried this command adding the RegKey (This command needs to be repeated for each 50 regkeys!):
New-ItemProperty -Path 'HKCU:\Software\AppName' -Name 'PresetFolder' -PropertyType String -Value '$env:userprofile\Documents\AppName\Presets1' -Force
New-ItemProperty -Path 'HKCU:\Software\AppName' -Name 'PresetFolder' -PropertyType String -Value '$env:userprofile\Documents\AppName\Presets2' -Force .......
When using "$env:userprofile" instead of c:\Users\MyUserProfile\Documents\.... the -value in the RegKey will be: "$env:userprofile\Documents\NewFolder\Presets" and not as wanted: "c:\Users\MyUserProfile\Documents\NewFolder\Presets".
I need a Variable for each userprofile!
Alternatively I can after Program installation by using admin-account, I can exported all RegKey's as a .reg-file. Before using the powershell-script to merge the RegKeys everytime a user is logging in Windows, I now need to search and replace the value of the path (-Value) from AdminUserProfil-path into a variable for each user running the script.
Part of the Reg-file:
[HKEY_CURRENT_USER\Software\AppName\Version]
"HelpDocPath"="C:\Users\\AdminUserprofiles\\Documents\\AppName\\Version\\HTML Help\\en"
"ExciterCacheInstallPath"="C:\\Program Files\\AppName\\Version\\Exciter Cache"
"DSPResourceFilesInstallPath"="C:\\Program Files\\AppName\\Version/Resources"
"InstallPath"="C:\\Program Files\\AppName\\InstallFolder"
"PresetFolder"="C:\\Users\\AdminUserprofiles\\Documents\\AppName\\Version\\Presets\\Global Presets"\
Hope anyone can help?
What do I need to type for the right path, so each user will have there own path? Do I need a variable fo rusers or..?
Thank you.
Define $env:USERPROFILE as a variable so you can call it, otherwise PS will just output what you have typed, which is what is happening in this case.
$path = "$env:USERPROFILE"
New-ItemProperty -Path 'HKCU:\Software\AppName' -Name 'PresetFolder' -PropertyType String -Value '$path\Documents\AppName\Presets1' -Force
I have been given the task to write a PS script that will, from a list of machines in a text file:
Output the IP address of the machine
Get the version of the SCCM client on the machine
Produce a GPResult HTMl file
OR
Indicate that the machine is offline
With a final stipulation of running the script in the background (Job)
I have the scriptblock that will do all of these things, and even have the output formatted like I want. What I cannot seem to do, is get the scriptblock to call the source file from within the same directory as the script. I realize that I could simply hard-code the directories, but I want to be able to run this on any machine, in any directory, as I will need to use the script in multiple locations.
Any suggestions?
Code is as follows (Note: I am in the middle of trying stuff I gathered from other articles, so it has a fragment or two in it [most recent attempt was to specify working directory], but the core code is still there. I also had the idea to declare the scriptblock first, like you do with variables in other programming languages, but more for readability than anything else):
# List of commands to process in job
$ScrptBlk = {
param($wrkngdir)
Get-Content Hostnames.txt | ForEach-Object {
# Check to see if Host is online
IF ( Test-Connection $_ -count 1 -Quiet) {
# Get IP address, extracting only IP value
$addr = (test-connection $_ -count 1).IPV4Address
# Get SCCM version
$sccm = (Get-WmiObject -NameSpace Root\CCM -Class Sms_Client).ClientVersion
# Generate GPResult HTML file
Get-GPResultantSetOfPolicy -computer $_.name -reporttype HTML -path ".\GPRes\$_ GPResults.html"}
ELSE {
$addr = "Offline"
$sccm = " "}
$tbl = New-Object psobject -Property #{
Computername = $_
IPV4Address = $addr
SCCM_Version = $sccm}}}
# Create (or clear) output file
Echo "" > OnlineCheckResults.txt
# Create subdirectory, if it does not exist
IF (-Not (Get-Item .\GPRes)) { New-Item -ItemType dir ".\GPRes" }
# Get current working directory
$wrkngdir = $PSScriptRoot
# Execute script
Start-Job -name "OnlineCheck" -ScriptBlock $ScrptBlk -ArgumentList $wrkngdir
# Let job run
Wait-Job OnlineCheck
# Get results of job
$results = Receive-Job OnlineCheck
# Output results to file
$results >> OnlineCheckResults.txt | FT Computername,IPV4Address,SCCM_Version
I appreciate any help you may have to offer.
Cheers.
~DavidM~
EDIT
Thanks for all the help. Setting the working directory works, but I am now getting a new error. It has no line reference, so I am not sure where the problem might be. New code below. I have moved the sriptblock to the bottom, so it is separate from the rest of the code. I thought that might be a bit tidier. I do apologize for my earlier code formatting. I will attempt to do better with the new example.
# Store working directory
$getwkdir = $PWD.Path
# Create (or clear) output file
Write-Output "" > OnlineCheckResults.txt
# Create subdirectory, if it does not exist. Delete and recreate if it does
IF (Get-Item .\GPRes) {
Remove-Item -ItemType dir "GPRes"
New-Item -ItemType dir "GPRes"}
ELSE{
New-Item -ItemType dir "GPRes"}
# Start the job
Start-Job -name "OnlineCheck" -ScriptBlock $ScrptBlk -ArgumentList $getwkdir
# Let job run
Wait-Job OnlineCheck
# Get results of job
$results = Receive-Job OnlineCheck
# Output results to file
$results >> OnlineCheckResults.txt | FT Computername,IPV4Address,SCCM_Version
$ScrptBlk = {
param($wrkngdir)
Set-Location $wrkngdir
Get-Content Hostnames.txt | ForEach-Object {
IF ( Test-Connection $_ -count 1 -Quiet) {
# Get IP address, extracting only IP value
$addr = (test-connection $_ -count 1).IPV4Address
# Get SCCM version
$sccm = (Get-WmiObject -NameSpace Root\CCM -Class Sms_Client).ClientVersion
Get-GPResultantSetOfPolicy -computer $_.name -reporttype HTML -path ".\GPRes\$_ GPResults.html"}
ELSE {
$addr = "Offline"
$sccm = " "}
$tbl = New-Object psobject -Property #{
Computername = $_
IPV4Address = $addr
SCCM_Version = $sccm}}}
Error text:
Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Provide an argument that
is not null or empty, and then try the command again.
+ CategoryInfo : InvalidData: (:) [Test-Connection], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.TestConnectionCommand
+ PSComputerName : localhost
As Theo observes, you're on the right track by trying to pass the desired working directory to the script block via -ArgumentList $wrkngdir, but you're then not using that argument inside your script block.
All it takes is to use Set-Location at the start of your script block to switch to the working directory that was passed:
$ScrptBlk = {
param($wrkngdir)
# Change to the specified working dir.
Set-Location $wrkngdir
# ... Get-Content Hostnames.txt | ...
}
# Start the job and pass the directory in which this script is located as the working dir.
Start-Job -name "OnlineCheck" -ScriptBlock $ScrptBlk -ArgumentList $PSScriptRoot
In PSv3+, you can simplify the solution by using the $using: scope, which allows you to reference variables in the caller's scope directly; here's a simplified example, which you can run directly from the prompt (I'm using $PWD as the desired working dir., because $PSScriptRoot isn't defined at the prompt (in the global scope)):
Start-Job -ScriptBlock { Set-Location $using:PWD; Get-Location } |
Receive-Job -Wait -AutoRemove
If you invoke the above command from, say, C:\tmp, the output will reflect that path too, proving that the background job ran in the same working directory as the caller.
Working directories in PowerShell background jobs:
Before PowerShell 7.0, starting background jobs with Start-Job uses the directory returned by [environment]::GetFolderPath('MyDocuments') as the initial working directory, which on Windows is typically $HOME\Documents, whereas it is just $HOME on Unix-like platforms (in PowerShell Core).
Setting the working dir. for the background job via Start-Job's -InitializationScript script-block argument via a $using: reference - e.g., Start-Job -InitializationScript { $using:PWD } { ... } should work, but doesn't in Windows PowerShell v5.1 / PowerShell [Core] 6.x, due to a bug (the bug is still present in PowerShell 7.0, but there you can use -WorkingDirectory).
In PowerShell (Core) 7+, Start-Job now sensibly defaults to the caller's working directory and also supports a -WorkingDirectory parameter to simplify specifying a working directory.
In PowerShell (Core) 6+ you can alternatively start background jobs with a post-positional & - the same way that POSIX-like shells such as bash do - in which case the caller's working directory is inherited; e.g.:
# PS Core only:
# Outputs the caller's working dir., proving that the background job
# inherited the caller's working dir.
(Get-Location &) | Receive-Job -Wait -AutoRemove
If I understand correctly, I think that the issue you are having is because the working directory path is different inside the execution of the Script Block. This commonly happens when you execute scripts from Scheduled tasks or pass scripts to powershell.exe
To prove this, let's do a simple PowerShell code:
#Change current directory to the root of C: illustrate what's going on
cd C:\
Get-Location
Path
----
C:\
#Execute Script Block
$ScriptBlock = { Get-Location }
$Job = Start-Job -ScriptBlock $ScriptBlock
Receive-Job $Job
Path
----
C:\Users\HAL9256\Documents
As you can see the current path inside the execution of the script block is different than where you executed it. I have also seen inside of Scheduled tasks, paths like C:\Windows\System32 .
Since you are trying to reference everything by relative paths inside the script block, it won't find anything. One solution is to use the passed parameter to change your working directory to something known first.
Also, I would use $PWD.Path to get the current working directory instead of $PSScriptRoot as $PSScriptRoot is empty if you run the code from the console.
I have a cute little script in my $PROFILE helping me start Notepad++ from the script showing a file of my choosing.
function Edit{
param([string]$file = " ")
Start-Process "C:\Program Files\Notepad++\notepad++.exe" -ArgumentList $file
}
It's worked great until recently, where I jump between different systems. I discovered that NPP is installed in C:\Program Files on some systems but in C:\Program Files (x86) on others. I can edit the script adapting it but having done so a gazillion times (i.e. 5 to this point), I got sick and tired of it, realizing that I have to automate this insanity.
Knowing little about scripting, I wonder what I should Google for. Does best practice dictate using exception handling in such a case or is it more appropriate to go for conditional expressions?
According to Get-Host | Select-Object Version I'm running version 5.1, if it's of any significance. Perhaps there's an even neater method I'm unaware of? Relying on an environment variable? I'd also prefer to not use a method valid in an older version of PS, although working, if there's a more convenient approach in a later one. (And given my experience on the subject, I can't tell a duck from a goose.)
I would use conditionals for this one.
One option is to test the path directly if you know for certain it is in a particular location.
Hard coded paths:
function Edit{
param([string]$file = " ")
$32bit = "C:\Program Files (x86)\Notepad++\notepad++.exe"
$64bit = "C:\Program Files\Notepad++\notepad++.exe"
if (Test-Path $32bit) {Start-Process -FilePath $32bit -ArgumentList $file}
elseif (Test-Path $64bit) {Start-Process -FilePath $64bit -ArgumentList $file}
else {Write-Error -Exception "NotePad++ not found."}
}
Another option is pulling path information from registry keys, if they're available:
function Edit{
param([string]$file = " ")
$32bit = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Notepad++\' -ErrorAction SilentlyContinue).("(default)")
$64bit = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\WOW6432Node\Notepad++\' -ErrorAction SilentlyContinue).("(default)")
if ($32bit) {Start-Process -FilePath "$32bit\notepad++.exe" -ArgumentList $file}
elseif ($64bit) {Start-Process -FilePath "$64bit\notepad++.exe" -ArgumentList $file}
else {Write-Error -Exception "NotePad++ not found."}
}
Based on the great help from #BoogaRoo (who should get some +1 for effort) and asked by the same to post my own version of the answer, I go against my reluctance to post asnwers to own questions due to strong sensation of tackiness.
My final version, taking into account systems that lack NP++ but still want to show the editor of some kind.
function Edit{
param([string]$file = " ")
$executable = "Notepad++\notepad++.exe"
$32bit = "C:\Program Files (x86)\" + $executable
$64bit = "C:\Program Files\" + $executable
$target = "notepad"
if(Test-Path $32bit) { $target = $32bit }
if(Test-Path $64bit) { $target = $64bit }
Start-Process $target -ArgumentList $file
}
Let me offer a streamlined version that also supports passing multiple files:
function Edit {
param(
# Allow passing multiple files, both with explicit array syntax (`,`-separated)
# or as indiv. arguments.
[Parameter(ValueFromRemainingArguments)]
[string[]] $File
)
# Construct the potential Notepad++ paths.
# Note: `-replace '$'` is a trick to append a string to each element
# of an array.
$exePaths = $env:ProgramFiles, ${env:ProgramFiles(x86)} -replace '$', '\Notepad++\notepad++.exe'
# See which one, if any, exists, using Get-Command.
$exeToUse = Get-Command -ErrorAction Ignore $exePaths | Select-Object -First 1
# Fall back to Notepad.
if (-not $exeToUse) { $exeToUse = 'notepad.exe' }
# Invoke whatever editor was found with the optional file(s).
# Note that both Notepad++ and NotePad can be invoked directly
# without blocking subsequent commands, so there is no need for `Start-Process`,
# whose argument processing is buggy.
& $exeToUse $File
}
An array of potential executable paths is passed to Get-Command, which returns a command-info object for each actual executable found, if any.
-ErrorAction Ignore quietly ignores any errors.
Select-Object -First 1 extracts the first command-info object, if present, from the Get-Command output; this is necessary to guard against the (perhaps unlikely) case where the executable exists in both locations.
$exeToUse receives $null (effectively) if Get-Command produces no output, in which case Boolean expression -not $exeToUse evaluates to $true, causing the fallback to notepad.exe to take effect.
Both command names (strings) and command-info objects (instances of System.Management.Automation.CommandInfo or derived classes, as returned by Get-Command) can be executed via &, the call operator.
I am looking to use a powershell script to WMI query the computer during post-install of the imaging sequence via MDT/SCCM. Actively there are multiple VB scripts to accomplish parts of the System Properties area (Manufacturer, Model, InstallDate, SerialNumber, etc.), and would like to consolidate this into a single script that does it all.
Running Powershell ISE as Administrator, so that wouldn't be causing for any permissions issues; the model information returns Macbook as I am testing on Windows 10 through Bootcamp.
Clear-Host
$Model = (Get-WmiObject -Class:Win32_ComputerSystem).Model
$RegKey = “HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\OEMInformation”
New-Item -Path $RegKey -Name Model -Type String -Value $Model –Force
After I ran the script, these were the results (shown below).
Name Property
----- --------
Model (default) : MacBookPro11,1
However the value is not written to the registry. How could I go about the writing of the informaiton to the registry, while also allowing for multiple variables to be aligned in addition? All the values (subkeys) would need to be created and be placed at the same Registry Path of "OEMInformation".
Aim to include for Manufacturer, Model, Name, InstallDate, SystemType as well.
If I understand you correctly, you're able to write to the registry, but you're unsure how to write multiple items to the same "path".
The Windows registry is contstructed by "Keys" and one or multiple values. Your "new-item" line above actually sets a value but you don't specify one so it looks like the "magic" default value is used.
In order to set multiple ones in the same path, you'd use the Cmdlet
Set-ItemProperty, for example using:
Set-ItemProperty -Path $RegKey -Name "Model" -value $Model
You can then have multiple "properties" in that path using the same technique (just use a different value for the "Name" parameter.
I was able to get this resolved, thank you #Trondh for the assistance.
$Model = (Get-WmiObject -Class:Win32_ComputerSystem).Model
$RegPath = 'Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\OEMInformation'
New-Item $RegPath -Force | New-ItemProperty -Name Model -Value $Model -Force | Out-Null
Hoping this will be an easy one for somebody, but I just don't have the experience. I'm pulling the mapped network drive info from a PC. I'm testing the path to make sure it's active and that the person still has access. The test works fine. Here's my issue...
If the test is $true, I want it to output a line of code to a new .ps1 file for remapping the drive. I think I'm just about there, but I can't wrap my head around outputting a line of code and not the output of the line. Thanks for any help!
foreach ($Drive IN $Drives)
{
$MND = $Network.OpenSubKey("$Drive")
$Share = $MND.GetValue("RemotePath")
$Path = Test-Path "$Share\*"
IF ($Path -eq $true)
{
$ErrorActionPreference = "SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"
Start-Transcript -path C:\output.ps1 -append
"New-PSDrive -Name "$Drive" -PSProvider FileSystem -Root "$Share" -Persist"
Stop-Transcript
}
}
Per your comment, you probably don't want to be using Start-Transcript (as you'd get a lot of header content that you don't want), but rather something that outputs to a file like Out-File -Append or Add-Content.
You also need to remove the internal double quotes which are likely unnecessary (or you could replace them with single quotes):
"New-PSDrive -Name $Drive -PSProvider FileSystem -Root $Share -Persist" | Add-Content c:\output.ps1
It's worth also checking you have rights to write files to the root of C:\, this is blocked by default for non-admins in later versions of Windows.