how to format output of expanded variable - variables

I am trying to make a variable equal the output of query but so i can pipe to another command but its not working as i hoped. here is what i have.
$office=get-aduser "samaccountname" -properties * | select office
I already tried using sub-expressions $folder= get-aduser "samaccountname" -properties * | select '$(office)' and
#{n='office';e={$_.office -replace '^office='$1'}} neither of which remove the #{office=}
My goal is to get $office=office but instead i get $office=#{office=}
How do you remove the #{} from the output?

This is what you need to do:
$office = (Get-ADUser "samAccountName" -properties office).Office
EDIT
Another way (which may or may not be easier to understand) is:
$user = Get-ADUser "samAccountName" -properties office
$office = $user.office

Related

Using PS to query SQL for list of users, then disable Active Directory accounts?

I'm trying to use Powershell to query SQL database for a list of suspended users, pipe into a variable, then use that to loop through and disable those AD accounts. Here's the code I'm using... note I'm just trying to write the output now instead of making a change so I don't do anything I regret.
Import-Module ActiveDirectory
$Users = Invoke-Sqlcmd -ServerInstance 'SERVER' -Database 'NAME' -Query "SELECT EmployeeID,
EmployeeStatus FROM [NAME].[dbo].[employee] WHERE EmployeeStatus = 'S'"
foreach ($user in $users)
{
Get-ADUser -Filter "EmployeeID -eq '$($user.EmployeeID)'" `
-SearchBase "OU=Logins,DC=domain,DC=com" |
#Set-ADUser -Identity $Name -Enabled $False
Write-Verbose $User
}
The SQL query is working fine, but when I run the loop it's giving this error:
Write-Verbose : The input object cannot be bound to any parameters for
the command either because the
command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline
input.
Am I just formatting this incorrectly? Or is there another way I should be thinking of this?
Thanks in advance!
If you would like to find inactive user accounts in Active Directory, you can use the Search-ADAccount cmdlet. You need to do this use the “-AccountInActive” parameter with Search-ADAccount.
PowerShell command below:
Search-ADAccount –AccountInActive –TimeSpan 120:00:00:00 –ResultPageSize 2000 –ResultSetSize $null | ?{$_.Enabled –eq $True} | Select-Object Name, SamAccountName, DistinguishedName | Export-CSV “C:\Temp\InActiveADUsers.CSV” –NoTypeInformation
I have given timespan for 120days and export the list into csv file.

Powershell parameter to variables into a command

I tried to find a way to join or use variable into a command.
I'm trying to create a command that accept parameters:
The command: aduser.ps1 John
aduser.ps1 script:
Param($User)
Get-AdUser -filter 'Name -like "*$user*"'
I had error and not sure what operator to use to join in the $user variables, i tried + or & and not working for me.
Variables will not expand inside single quote strings, replace them with double quotes:
Get-AdUser -filter "Name -like '*$user*'"

Powershell - listing folders in mulitple places and changing files in those places

I'm trying to set up a script designed to change a bit over 100 placeholders in probably some 50 files. In general I got a list of possible placeholders, and their values. I got some applications that have exe.config files as well as ini files. These applications are stored in c:\programfiles(x86)\ and in d:\In general I managed to make it work with one path, but not with two. I could easily write the code to replace twice, but that leaves me with a lot of messy code and would be harder for others to read.
ls c:\programfiles(x86) -Recurse | where-object {$_.Extension -eq ".config" -or $_.Extension -eq ".ini"} | %{(gc $PSPath) | %{
$_ -replace "abc", "qwe" `
-replace "lkj", "hgs" `
-replace "hfd", "fgd"
} | sc $_PSPath; Write-Host "Processed: " + $_.Fullname}
I've tried to include 2 paths by putting $a = path1, $b = path2, c$ = $a + $b and that seems to work as far as getting the ls command to run in two different places. however, it does not seem to store the path the files are in, and so it will try to replace the filenames it has found in the folder you are currently running the script from. And thus, even if I might be in one of the places where the files is supposed to be, it's not in the other ...
So .. Any idea how I can get Powershell to list files in 2 different places and replace the same variables in both places without haveing to have the code twice ? I thought about putting the code I would have to use twice into a variable, calling it when I needed to instead of writing it again, but it seemed to resolve the code before using it, and that didn't exactly give me results since the data comes from the first part.
If you got a cool pipeline, then every problem looks like ... uhm ... fluids? objects? I have no clue. But anyway, just add another layer (and fix a few problems along the way):
$places = 'C:\Program Files (x86)', 'D:\some other location'
$places |
Get-ChildItem -Recurse -Include *.ini,*.config |
ForEach-Object {
(Get-Content $_) -replace 'abc', 'qwe' `
-replace 'lkj', 'hgs' `
-replace 'hfd', 'fgd' |
Set-Content $_
'Processed: {0}' -f $_.FullName
}
Notable changes:
Just iterate over the list of folders to crawl as the first step.
Doing the filtering directly in Get-ChildItem makes it faster and saves the Where-Object.
-replace can be applied directly to an array, no need for another ForEach-Object there.
If the number of replacements is large you may consider using a hashtable to store them so that you don't have twenty lines of -replace 'foo', 'bar'.

How do I get the value of a registry key and ONLY the value using powershell

Can anyone help me pull the value of a registry key and place it into a variable in PowerShell? So far I have used Get-ItemProperty and reg query and although both will pull the value, both also add extra text. I need just the string text from the registry key and ONLY the string text from the key. I'm sure I could create a function to strip off the extra text but if something changes (i.e. reg key name) it might affect this.
$key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion'
(Get-ItemProperty -Path $key -Name ProgramFilesDir).ProgramFilesDir
I've never liked how this was provider was implemented like this : /
Basically, it makes every registry value a PSCustomObject object with PsPath, PsParentPath, PsChildname, PSDrive and PSProvider properties and then a property for its actual value. So even though you asked for the item by name, to get its value you have to use the name once more.
NONE of these answers work for situations where the value name contains spaces, dots, or other characters that are reserved in PowerShell. In that case you have to wrap the name in double quotes as per http://blog.danskingdom.com/accessing-powershell-variables-with-periods-in-their-name/ - for example:
PS> Get-ItemProperty Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7
14.0 : C:\Program Files (x86)\Microsoft Visual Studio 14.0\
12.0 : C:\Program Files (x86)\Microsoft Visual Studio 12.0\
11.0 : C:\Program Files (x86)\Microsoft Visual Studio 11.0\
15.0 : C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\
PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\V
S7
PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS
PSChildName : VS7
PSProvider : Microsoft.PowerShell.Core\Registry
If you want to access any of the 14.0, 12.0, 11.0, 15.0 values, the solution from the accepted answer will not work - you will get no output:
PS> (Get-ItemProperty Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7 -Name 15.0).15.0
PS>
What does work is quoting the value name, which you should probably be doing anyway for safety:
PS> (Get-ItemProperty "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7" -Name "15.0")."15.0"
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\
PS>
Thus, the accepted answer should be modified as such:
PS> $key = "Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\VisualStudio\SxS\VS7"
PS> $value = "15.0"
PS> (Get-ItemProperty -Path $key -Name $value).$value
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\
PS>
This works in PowerShell 2.0 through 5.0 (although you should probably be using Get-ItemPropertyValue in v5).
Harry Martyrossian mentions in a comment on his own answer that the
Get-ItemPropertyValue cmdlet was introduced in Powershell v5, which solves the problem:
PS> Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion' 'ProgramFilesDir'
C:\Program Files
Alternatives for PowerShell v4-:
Here's an attempt to retain the efficiency while eliminating the need for repetition of the value name, which, however, is still a little cumbersome:
& {
(Get-ItemProperty `
-LiteralPath HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion `
-Name $args
).$args
} ProgramFilesDir
By using a script block, the value name can be passed in once as a parameter, and the parameter variable ($args) can then simply be used twice inside the block.
Alternatively, a simple helper function can ease the pain:
function Get-RegValue([String] $KeyPath, [String] $ValueName) {
(Get-ItemProperty -LiteralPath $KeyPath -Name $ValueName).$ValueName
}
Note: All solutions above bypass the problem described in Ian Kemp's's answer - the need to use explicit quoting for certain value names when used as property names; e.g., .'15.0' - because the value names are passed as parameters and property access happens via a variable; e.g., .$ValueName
As for the other answers:
Andy Arismendi's helpful answer explains the annoyance with having to repeat the value name in order to get the value data efficiently.
M Jeremy Carter's helpful answer is more convenient, but can be a performance pitfall for keys with a large number of values, because an object with a large number of properties must be constructed.
I'm not sure if this has been changed, or if it has something to do with which version of PS you're using, but using Andy's example, I can remove the -Name parameter and I still get the value of the reg item:
PS C:\> $key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion'
PS C:\> (Get-ItemProperty -Path $key).ProgramFilesDir
C:\Program Files
PS C:\> $psversiontable.psversion
Major Minor Build Revision
----- ----- ----- --------
2 0 -1 -1
Given a key \SQL with two properties:
I'd grab the "MSSQLSERVER" one with the following in-cases where I wasn't sure what the property name was going to be to use dot-notation:
$regkey_property_name = 'MSSQLSERVER'
$regkey = get-item -Path 'HKLM:\Software\Microsoft\Microsoft SQL Server\Instance Names\SQL'
$regkey.GetValue($regkey_property_name)
Well you need to be specific here. As far as I know, the key in a registry is a "folder" of properties. So did you mean get the value of a property? If so, try something like this:
(Get-ItemProperty HKLM:\Software\Microsoft\PowerShell\1\PowerShellEngine -Name PowerShellVersion).PowerShellVersion
First we get an object containing the property we need with Get-ItemProperty and then we get the value of for the property we need from that object. That will return the value of the property as a string. The example above gives you the PS version for "legacy"/compatibility-mdoe powershell (1.0 or 2.0).
Following code will enumerate all values for a certain Registry key, will sort them and will return value name : value pairs separated by colon (:):
$path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework';
Get-Item -Path $path | Select-Object -ExpandProperty Property | Sort | % {
$command = [String]::Format('(Get-ItemProperty -Path "{0}" -Name "{1}")."{1}"', $path, $_);
$value = Invoke-Expression -Command $command;
$_ + ' : ' + $value; };
Like this:
DbgJITDebugLaunchSetting : 16
DbgManagedDebugger : "C:\Windows\system32\vsjitdebugger.exe" PID %d APPDOM %d EXTEXT "%s" EVTHDL %d
InstallRoot : C:\Windows\Microsoft.NET\Framework\
Not sure at what version this capability arrived, but you can use something like this to return all the properties of multiple child registry entries in an array:
$InstalledSoftware = Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" | ForEach-Object {Get-ItemProperty "Registry::$_"}
Only adding this as Google brought me here for a relevant reason and I eventually came up with the above one-liner for dredging the registry.
If you create an object, you get a more readable output and also gain an object with properties you can access:
$path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework'
$obj = New-Object -TypeName psobject
Get-Item -Path $path | Select-Object -ExpandProperty Property | Sort | % {
$command = [String]::Format('(Get-ItemProperty -Path "{0}" -Name "{1}")."{1}"', $path, $_)
$value = Invoke-Expression -Command $command
$obj | Add-Member -MemberType NoteProperty -Name $_ -Value $value}
Write-Output $obj | fl
Sample output:
InstallRoot : C:\Windows\Microsoft.NET\Framework\
And the object:
$obj.InstallRoot = C:\Windows\Microsoft.NET\Framework\
The truth of the matter is this is way more complicated than it needs to be. Here is a much better example, and much simpler:
$path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\.NETFramework'
$objReg = Get-ItemProperty -Path $path | Select -Property *
$objReg is now a custom object where each registry entry is a property name. You can view the formatted list via:
write-output $objReg
InstallRoot : C:\Windows\Microsoft.NET\Framework\
DbgManagedDebugger : "C:\windows\system32\vsjitdebugger.exe"
And you have access to the object itself:
$objReg.InstallRoot
C:\Windows\Microsoft.NET\Framework\

How to use a PowerShell variable as command parameter?

I'm trying to use a variable as a command's parameter but can't quite figure it out. Let's say MyCommand will accept two parameters: option1 and option2 and they accept boolean values. How would I use $newVar to substitute option 1 or 2? For example:
$newVar = "option1"
MyCommand -$newVar:$true
I keep getting something along the lines of 'A positional parameter cannot be found that accepts argument '-System.String option1'.
More Specifically:
Here, the CSV file is an output of a different policy. The loop goes through each property in the file and sets that value in my policy asdf; so -$_.name:$_.value should substitute as -AllowBluetooth:true.
Import-Csv $file | foreach-object {
$_.psobject.properties | where-object {
# for testing I'm limiting this to 'AllowBluetooth' option
if($_.name -eq "AllowBluetooth"){
Set-ActiveSyncMailboxPolicy -Identity "asdf" -$_.name:$_.value
}}
}
Typically to use a variable to populate cmdlet parameters, you'd use a hash table variable, and splat it, using #
$newVar = #{option1 = $true}
mycommand #newVar
Added example:
$AS_policy1 = #{
Identity = "asdf"
AllowBluetooth = $true
}
Set-ActiveSyncMailboxPolicy #AS_policy1
See if this works for you:
iex "MyCommand -$($newVar):$true"
I had the same Problem and just found out how to resolve it. Solution is to use invoke-Expression: invoke-Expression $mycmd
This uses the $mycmd-string, replaces variables and executes it as cmdlet with given parameters
Nowadays, If you don't mind evaluating strings as commands, you may use Invoke-Expression:
$mycmd = "MyCommand -$($newVar):$true"
Invoke-Expression $mycmd
I would try with:
$mycmd = "MyCommand -$($newVar):$true"
& $mycmd
result
Can't work because the ampersand operator just execute single commands without prameters, or script blocks.