Setting a computer room number with a PowerShell script - powershell

Thank you all for your replies. I have corrected the errors in my code, although they were just a cut and paste error. Here is an example with the error I get. If I do for example:
PS > Set-ADComputer "VM-WINDOWS7" -Location "NA/HQ/Building A"
PS > Get-ADComputer "VM-WINDOWS7" -Properties location |select-object location
It works and I get the result:
Location
--------
NA/HQ/Building A
But when I do:
PS > Set-ADComputer "VM-WINDOWS7" -RoomNumber "7"
Or
PS > Set-ADComputer "VM-WINDOWS7" -RoomNumber #{Replace="7"}
I get the error:
Set-ADComputer: Cannot find a parameter that matches the name "RoomNumber".
At line: 1 Character: 41
+ Set-ADComputer "VM-WINDOWS7" -RoomNumber <<<< #{Replace="7"}
+ CategoryInfo: InvalidArgument: (:) [Set-ADComputer], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.ActiveDirectory.Management.Commands.SetADComputer
It’s like I said before, the parameter RoomNumber is not recognized, so I thought maybe it has another name, like for example ( Account name in AD = SAMAccountName in PowerShell ).

You have a couple of issues here for sure. You have mistyped the AD attribute roomNumber as rooomNumber. You also have a space where your hashtable is declared.
Much like ssaviers, I see some smart quotes as well. Those can usually come from a copy and paste but you need to be careful if those are in your code.
“ - smartquote
" - regular double quote
That being said the problematic part might just need to be updated:
Set-ADComputer "$HostName" -Replace #{roomNumber = "$RoomNumber"}

Found the answer:
Set-ADComputer doesn't have a -roomnumber parameter. But it can be modified using Add, Replace, Clear or Remove parameters.
The 'ROOMNUMBER' field is LDAP so it has a different syntax:
Set-ADComputer $HostName -replace #{roomNumber='$RoomNumber'} (that's what i used in the first place but i didn’t write it correctly)
Looks like a lot of the fields in AD especially for computers need to be done this way.
Anyway thank you all for your ideas and supports.
Cheers.

Related

Invoking command at dc - get gpinheritance - wont work

I am writing a script where a part of it needs to connect to domain controller and get all the gpo's currently linked to a specific OU.
the line that does that is:
Invoke-Command -Session $S -ScriptBlock {Get-GPInheritance -target $using:Switch -domain shahar.local -server dc01 }
$s= credentials, $switch is a a variable that contains an ou that was picked.
those variables exists and they are good.
the error i get is:
Value does not fall within the expected range.
+ CategoryInfo : NotSpecified: (:) [Get-GPInheritance], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException,Microsoft.GroupPolicy.Commands.GetGPInheritanceCommand
+ PSComputerName : DC01
can anyone please assist?
I'm posting this as answer, because IMO there are too many questions that remain 'unanswered' while the solution is given in a comment.
The error message triggered me to check if any of the variables you use perhaps is an Automatic variable and in this case it is the variable $switch.
Using a different self-defined variable name here like $selectedOU should solve the problem.

text manipulation with powershell

I'm trying to format the output of this command to get only the dfsnamespace only like that :
\\F-TYPHON\DATA13\AI-Project
I can not use the Get-DfsnFolderTarget cmdlet because the RSAT-DFS-Mgmt-Con
is not installed on all servers and I cannot install it .
$DFSPath="\\F-TYPHON\shared\AI-Project"
PS C:\> dfsutil client property state $DFSPath
Active, Online \\F-TYPHON\DATA13\AI-Project
Done processing this command.
I've tried this .
PS C:\> $dfs=dfsutil client property state $DFSPath
PS C:\> $dfs.trimstart("Active, Online")
Method invocation failed because [System.Object[]] doesn't contain a method named 'trimstart'.
At line:1 char:15
+ $dfs.trimstart <<<< ("Active, Online")
+ CategoryInfo : InvalidOperation: (trimstart:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
any help will be apreciated I can list all volume data for the filer but there's many incoherence in the structure so I need only to list the shared folder under "shared" on a filer and then procces it with dfsutil to get the absolut path
Use a regular expression to match the text output of dfsutil:
$DFSPath="\\F-TYPHON\shared\AI-Project"
if ((dfsutil client property state $DFSPath) -match "(?<=\s{2,})\\\\.*"){
$DFSNameSpace = $Matches.Value
}
here (?<=\s{2,})\\\\.* matches two or more whitespace \s in a lookbehind
followed by two (escaped) backslashes and the remainder of the line.
thank you for your help
i've found a solution that i can use in a way it's not 100% powershell but i can use it to extract the output in a format that i can use it in a loop and than make automated robocopylines with powershell
here the code for the output that i found
$DFSPath="\F-TYPHON\shared\AI-Project"
$dfspath=(dfsutil client property state $DFSPath |findstr /i \F-TYPHON)|out-string
$dfs=$dfspath.Trimstart("Active, Online ")
write-host $dfs
the output is
\F-TYPHON\DATA13\AI-Project
it's certainly not the best but i can work with it
if you have any others suggestion you're welcome

How to create a group with special characters using Powershell

I have been tasked with creating a number of active directory groups using PowerShell. The problem is all the group names contain double colons "::" (the naming standard was created long before I joined!).
When running the following command:
NEW-ADGroup –name "XX123::Test_Group_Creation" –groupscope Global –path "OU=TestOU,DC=TestDomain,DC=local"
The following error is received:
NEW-ADGroup : The name provided is not a properly formed account name
At line:1 char:1
+ NEW-ADGroup –name "XX123::Test_Group_Creation" –groupscope Global –path "OU=Test ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (CN=XX123::Test_...Domain,DC=local:String) [New-ADGroup], ADException
+ FullyQualifiedErrorId : The server is unwilling to process the request,Microsoft.ActiveDirectory.Management.Commands.NewADGroup
If you create the group manually (in the gui) you get the following warning but you are still able to create it:
How can I get around this issue. F.Y.I. I have tried to escape the colons with a back tick and also a forward slash, none of which have worked
The : character is not valid for the sAMAccountName attribute, so you need to replace : with another character (the GUI uses _) when creating the group. You can use the -replace operator to do this pretty easily in PowerShell.

Get-PrintConfiguration doesnt seem to work

I am trying to use Get-PrintConfiguration on a networked printer but for some reason it returns this error
Get-PrintConfiguration : The specified printer was not found. At
line:1 char:1
+ Get-PrintConfiguration -PrinterName "Printer1"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (MSFT_PrinterConfiguration:ROOT/StandardCi...erConfiguration)
[Get-PrintConfiguration], CimException
+ FullyQualifiedErrorId : HRESULT 0x80070709,Get-PrintConfiguration
Is there something I am missing? The Printer name is correct and im somewhat confident the syntax is correct.
Edit:
I just noticed the second line. If you're specifying a printer name by concatenating multiple strings, be sure to surround the concatenations with parenthese. Example:
Get-PrinterConfiguration -PrinterName ("Printer1" + "-PC1")
Hope some of this helps.
Original:
Only posting this as an answer since I don't have enough reputation to make a comment, but in order to get a proper answer, could you provide more details, please? Perhaps a code/script example?
This worked for me to get a network printer configuration
Get-Printer | Where-Object -Property 'Name' -EQ 'Sharp MX-4140N' | Get-PrintConfiguration
PrinterName ComputerName Collate Color DuplexingMode
----------- ------------ ------- ----- -------------
Sharp MX-4140N True True OneSided
Note: computer name blanked intentionally.

Commands executed in PowerShell with variables surrounded in quotes fail. Why?

I'm having a surprisingly difficult time embedding variables with quotes to an external command with PoSH. For example, this command
dfsradmin membership list /rgname:`"stuff I want`"
gives me the following expected result:
Failed:
Replication group with name stuff I want cannot be found.
This command, however
$group = "stuff I want"
dfsradmin membership list /rgname:`"$group`"
fails with this error:
Failed:
The subobject "/rgname:"stuff is not a valid subobject.
Is this a bug with Powershell or am I missing/misunderstanding something?
Yeah there are known issues in Powershell ( including v2.0) around this: http://connect.microsoft.com/PowerShell/feedback/details/376207/executing-commands-which-require-quotes-and-variables-is-practically-impossible
See if the alternatives discussed in the link above work for you. I cannot try it out as I don't have that executable.
Also echoargs.exe is a useful tool that you can use to see what arguments have been recevied from Powershell.
I found that defining
$quote = '"'
and then using /command$quote"test"$quote works as well
There's no need to add back ticks in front of quotes. Does this work for you?
$group = "stuff I want"
dfsradmin membership list /rgname:"$group"
So I was able to get around this by executing it in CMD.exe and doing string manipulations to get what I need.
$str = &cmd /c 'dfsradmin membership list /rgname:"blah blah"'
$str = &cmd /c "dfsradmin membership list /rgname:$blah" # with vars
Thanks for the help! I hope this has been resolved in Powershell 3.0.
I found a workaround which doesn't call cmd but uses Invoke-Expression instead. The command has to be put in a variable first:
$var = "string with spaces"
$command = "first part " + [char]96 + [char]34 + $var + [char]96 + [char]34 + " second part"
Invoke-Expression $command
Not that pretty but it works. You can replace [char]96 with '`' and [char]34 with '"' if you prefer. Easy to create a function which does it if you use it a lot.
All of the above did not work for me but based on Carlos idea, this is the solution that worked posted here
# get msdeploy exe
$MSDeploy = ${env:ProgramFiles}, ${env:ProgramFiles(x86)} |
ForEach-Object {Get-ChildItem -Path $_ -Filter 'MSDeploy.exe' -Recurse} |
Sort-Object -Property #{Expression={[version]$_.VersionInfo.FileVersion}} -Descending |
Select-Object -First 1 -ExpandProperty FullName
#build deploy command
$deplyCmd = """""$MSDeploy"" -verb:sync -dest:iisApp=""Default Web Site"" -enableRule:DoNotDeleteRule -source:iisApp=""$ExtraWebFilesFolder"""
#execute
&cmd /c $deplyCmd
I know this is old thread but just posting here in case my solution works for somebody as it worked for me.
This particular command (dfsradmin) expects natively seen quotes so I just enclosed value with quotes in single quotes thus passing quotes as well:
dfsradmin membership list /rgname:'"stuff I want"'
or if using through variable:
$group = '"stuff I want"'
dfsradmin membership list /rgname:$group