Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Powershell didn’t pay attention in mathematics!?

$
0
0

Hi All,

a short PS question witch I can’t explain.

#########################################################

$myA="0.40"

$myB="1.03"

$myA= ([double]($myA))

$myB= ([double]($myB))

$mySum=$myA+$myB

$mySum|Export-ClixmlC:\Temp\test1.xml -EncodingUTF8

#########################################################

#Export in File = <Db>1.4300000000000002</Db>

#########################################################

#########################################################

$myA="0.40"

$myB="1.02"

$myA= ([double]($myA))

$myB= ([double]($myB))

$mySum=$myA+$myB

$mySum|Export-ClixmlC:\Temp\test2.xml -EncodingUTF8

#########################################################

#Export in File = <Db>1.42</Db>

#########################################################

Why the F* is 0.40 + 1.03 = 1.4300000000000002
The value in PS is correct -> only if I exported them to XML the value is incorrect and only for 1.43?

Is there some “Feature” I don’t know? Can someone explain this to me?

Many thanks in advance.

Kind regards
David


MBAM - 2.5

$
0
0

Please, i need some documentation and implementation guide of MBAM, something easy and clear to understand, Anyone has it?

Thank you

check if registry key exists using wmi class in powershell

$
0
0

Dear All

Im using WMI stdRegProv in powershell to get the remote registry information. Im able to get the registry values but i should check whether the registry path exits or not ? eg:hklm\software\microsoft  exits. please help

Thanks in advance

test-connect blocks of machines?

$
0
0

Since NetSend is gone in Windows 7 we (like many others) still need to send broadcast messages to our environment.   I found the code below which works.   It allows me to send a MSG.EXE message to machines.   But the issue is I need to run test-connect first since I only want to send this Function to online machines.   

I know there are smart people on this forum and what I need help with is this:   if I want to send a House-Wide message I would of course get a list of machines from AD.    The variable below called$mypc would run Get-ADComputer etc...etc...  so now lets assume $pc has 2,000 workstation names within it.

How do I run test-connect against $pc but not one-at-a-time?  I want to ping blocks of machines and if they are online how would I then call this function below?

My goal is to send a message to every online Windows 7 machines within 90 seconds.   


Function Send-NetMessage {

Param(
    [Parameter(Mandatory=$True)]
    [String]$Message,
    
    [String]$Session="*",
    
    [Parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
    [Alias("Name")]
    [String[]]$Computername=$env:computername,
    
    [Int]$Seconds="5",
    [Switch]$VerboseMsg,
    [Switch]$Wait
    )
    
Begin
    {
    Write-Verbose "Sending the following message to computers with a $Seconds second delay: $Message"
    }
    
Process
    {
    ForEach ($Computer in $ComputerName)
        {
        Write-Verbose "Processing $Computer"
        $cmd = "msg.exe $Session /Time:$($Seconds)"
        if ($Computername){$cmd += " /SERVER:$($Computer)"}
        if ($VerboseMsg){$cmd += " /V"}
        if ($Wait){$cmd += " /W"}
        $cmd += " $($Message)"

        Invoke-Expression $cmd
        }
    }
End
    {
    Write-Verbose "Message sent."
    }
}


$msg1 = Read-Host "enter a message"
$mypc = @("mg2014","cclab2","MG11751","mg10462","mg11768","mg11786","mg11741","mg13244","mg13434","mg14464", "mg10257")
$mypc | Send-NetMessage $msg1 -Seconds 30 -VerboseMsg


mqh7

Updating AD User RDS settings with PowerShell

$
0
0

Hi,

I have a simple script that I'm using to do bulk changes to ad users rds settings. Script reads user names from text file and modifies settings from the users listed in file. Is there a way to get this script to search users from all OU's under the specified root OU? 

$Userlist = Get-Content "C:\Temp\users.txt"

	    ForEach ($UserName in $UserList) {

		$TsProfilePath = "\\DFS\Share\$UserName"
	        $user = [ADSI]"LDAP://CN=$Username,OU=Users,OU=xxx,DC=corp,DC=xxxx,DC=com"
	        $user.psbase.invokeSet("TerminalServicesProfilePath",$TsProfilePath)
	        $user.setinfo()

	    }


Formatting output from SQL query

$
0
0
Hi,

What I am trying to do is query a View in a SQL database and export the result to a CSV file.

Connecting to the SQL database and running the query works and I can store the result in a DataTable in PowerShell.
But the issue is with how some of tha data returned is formated in PowerShell.

When I run my query using SQL Server Management Studio (SSMS) I get the formatting I am looking for.

Here are two examples

1)
In SSMS: 2016-01-01
In the DataTable: 2016-01-01 00:00:00

2)
In SSMS: 123.50
In the DataTable: 123,50 (comma instead of dot)

Is there any way for me to just save it as it is stored in the databse table?


equivalent of the cat command but reading from stdin and writing to stdout using byte encoding

$
0
0

I'm looking for how to do the equivalent of 

cat >output

but where byte encoding is used. This reads from stdin and writes to stdout with redirection to a file.

Thanks


-owhall

Remote-Powershell-Session over Certificate Authentication on Win 2012 R2 Standard

$
0
0

Hello,

I am currently trying to gain a remote access to one of our Windows 2012 R2 Standard servers by using certificates and Powershell.


Introduction of the participating servers:

  1. The server I wish to access (I’ll call it aim-server in the following) is inside of our DMZ, last time it got any new Microsoft Updates has been march 2015 and it is running a Powershell Version 4.0. Its name contains an underline (“_”) and a three numbers, it is part of a working group.
  2. The server I use to access it from (in the following I will refer to it as source-server) is a Windows 2012 R2 Standard as well, last time updated this year at april and part of our domain, running a Powershell Version 4.0 as well.
  3. I have been successful accessing another server inside said DMZ already that is a Windows 2012 R2, PS Version 4.0, updated in april 2016 and part of a workgroup (another workgroup as the problematic server though).

 

Way of accessing:

Steps executed on the aim-server:

  1. I create a local user called “service” using the mmc, give it a password that won’t expire and add it to the local group: “Administrators”
  2. I open the PS as an administrator and execute
    1. Enable-PSRemoting –Force
    2. Set-Item wsman:\localhost\client\trustedhosts *
    3. Restart-Service WinRM

 Steps executed on the aim-server:

  1. I create a listener for the HTTPS transport using the CMD and following command:winrm create winrm/config/Listener?Address=*+Transport=HTTPS @{Hostname="<Name of the aim-server>";CertificateThumbprint="‎‎‎<Thumbprint of the aim-server-certificate>‎‎‎‎‎‎‎‎‎"}
  2. I add a rule to the aim-server-firewall by using the following command on the CMD: netsh advfirewall firewall add rule name="Windows-Remoteverwaltung (HTTPS eingehend)" dir=in action=allow program=System enable=yes profile=domain protocol=tcp localport=5986 (Yes, it says profile=domain but I already manually set the profile possibilities to private and public as well already!)

 Steps executed on source-server:

  1. I test the remote access via PS using Credentials with the following PS-command: Enter-PSSession –ComputerName <Name of the aim-server> -Credential (Get-Credential) –USESSL This WORKED just fine!
  2. I exit the session (“Exit-PSSession”)

 Steps executed on the aim-server:

  1. Now I do the certmapping. Therefore I use the Powershell again, typing the following command: New-Item -Path WSMan:\localhost\ClientCertificate -Credential (Get-Credential) -Subject <name source-server> -URI * -Issuer <Thumbprint of our issuer certificate> -Force A popup window appears in which I type in the login data of “service”
  2. Once that is done I allow the cert authentication via CMD: winrm set winrm/config/service/auth @{Certificate="true"}

 

Step executed on the source-server:

1. I try to test the access now by executing the following in the Powershell (run as administrator of course):Enter-PSSession –Computername <name of the aim-server> -CertificateThumbprint <thumbprint of the source-server>

 

No matter what I tried so far (and that has been a lot, I’ll come to that later), I always get the following error message:

 

Here are some of my trials so far (including restarts where they are needed):

 

  • I tried to change the certmapping to the predefined local administrator account
  • I adjusted the UAC to be on the same status as on the other server on which the whole procedure works just fine
    • I checked the regedit-entry (at Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System „LocalAccountTokenFilterPolicies“ ) which appears and there was no difference as well
  • I switched the Kerberos Authentication off
  • Logged in with “service” to create the folders etc.
  • Added all different names (dns) of the aim-server to the certificate
  • Tried different names for our aim-server
  • I checked the Certificate and took care that it
    • is up to date
    • contains the necessary key usage and extended key usage
    • checked all data like the name and so on to make sure there are no typos etc.
    • was imported to the necessary folders using mmc
  • Changed the group of “service” to “remote management users”
  • Checked if the aim-server can access the certificate revocation list
  • Using the IP instead of the server-name for testing the certificate-based access
  • Setting the rights of “service” manually (different ways, e.g. via PS or system management)
  • Recreated “service” and tried different passwords that did or did not include e.g. specific signs
  • Redone all steps a few times to make sure it hasn’t just been a typo somewhere
  • Checked the group policies
 

I would prefer an access-way that does NOT include an update of the servers if possible. I anyway appreciate any helpful comments though.

Best wishes and merry christmas!



Need Help in PowerShell Script. Trying to get the userprincipalname, msRTCSIP-PrimaryUserAddress of 300 AD users

$
0
0

The below command is not working. please help on this command.

Get-Content'C:\Users\Chinauser.txt' |%{Get-ADUser$user_-ServerXYZ.com}|selectuserprincipalname,msRTCSIP-PrimaryUserAddress.

 

SQL AlwaysOn with Powershell

$
0
0

Hi guys, I'm stuck with a problem during the creation of an Availability Group with Powershell.

I have 2 Windows Server 2012R2 ("CODER5", primary / "CODER4" secondary) in the same subnet, joined in the same domain. 

The Failover cluster will be created with the first lines of the script, and it work correctly.

They both have installed a version of SQL Server 2012 Enterprise with the DEFAULT instance name

This is the script that I have created but it failed, it works until the last line

Install-WindowsFeature Failover-Clustering,NET-Framework-Core
Test-Cluster –Node CODER4, Coder5
New-Cluster –Name MyCluster –Node coder2, coder3 –StaticAddress 10.1.1.11
Get-ClusterNode
foreach ($node in Get-ClusterNode) {Enable-SqlAlwaysOn -ServerInstance $node -Force}
Import-Module sqlps -Verbose
cd SQLServer:\SQL\$env:CODER5
$PrimaryServer = Get-Item "SQLSERVER:\SQL\coder5\default"
$SecondaryServer = Get-Item "SQLSERVER:\SQL\coder4\default"
$PrimaryReplica = New-SqlAvailabilityReplica -Name "coder5\default" -EndpointUrl "TCP://coder5.testha.local:5022" -FailoverMode "Automatic" -AvailabilityMode "SynchronousCommit" -AsTemplate -Version ($PrimaryServer.Version)

$SecondaryReplica = New-SqlAvailabilityReplica -Name "coder4\default" -EndpointUrl "TCP://coder4.testha.local:5022" -FailoverMode "Automatic" -AvailabilityMode "SynchronousCommit" -AsTemplate -Version ($SecondaryServer.Version)

New-SqlAvailabilityReplica : Cannot process argument transformation on parameter 'Version'. Object reference not set
to an instance of an object.
At line:1 char:202
+ ... plate -Version ($SecondaryServer.Version)
+                    ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [New-SqlAvailabilityReplica], ParameterBindingArgumentTransformationExc
   eption
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,Microsoft.SqlServer.Management.PowerShell.Hadr.NewS
   qlAvailabilityReplicaCommand

I will appreciate your help

Thank you very much

MR


dsdbutil output to XAML TextBox

$
0
0

Hi All,

We are managing a couple of AD LDS instances and I would like to write a script which lists the instances. I'm also creating a GUI for this in XAML.

So far, I'm able to catch the output of dsdbutil list instances, but it looks weird in the textbox. Here is my code:

c:\VisualStudio\Scripts\LoadDialog.ps1 -XamlPath 'c:\VisualStudio\Forms\MyForm.xaml'

$MyButton.add_Click({
$MytextBox.Text = ""
$output = dsdbutil.exe "List Instances" quit

foreach ($data in $output)
{
    $MytextBox.Text += "["
    $MytextBox.Text += $($data | ConvertFrom-String -Delimiter ": " -PropertyNames Name, Value).Name | Out-String
    $MytextBox.Text += " : "
    $MytextBox.Text += $($data | ConvertFrom-String -Delimiter ": " -PropertyNames Name, Value).Value | Out-String
    $MytextBox.Text += "]"
}

})

$xamGUI.ShowDialog() | Out-Null

The output looks like this:

It's quite messy and there are empty lines too.

Could you help me how to handle this output in the textbox to be tidy?

Thank you & Kind regards,

Dvijne

Monitor Memory performance(SOLVED)

$
0
0

Hi all,

Please, I need some help to find some powershell cmdlets that will help me to monitor the following "MEMORY" metrics :

* Per-Process Handle Count (Count)

* Per-Process Memory Usage(MB)

* Per-Process Page Faults Per Second (Count) 

* Per-Process Pool Non-paged Bytes (Count)

Thanks in advance!


cant call variable in Invoke-Command Script block

$
0
0

Hi All,

I have got some script which takes my credentials, creates a text box for users input and then passes that input to a variable and then runs an invoked command calling the credentials and user value. 

Everything is working bar the user input variable. 

How can I take the variable from the user input and call it in the Invoked-Command?

Thanks. 


IT Professional

pass arg to workflow

$
0
0

I am  using a Workflow and within this workflow I want to send a MSG.EXE to remote machines.   I have tried to place a Read-Host command within the Workflow Loop and it gives me an error saying you can't do that.  So I moved my Read-Host Outside the  Workflow Loop and it still does not work.  No MSG ever gets sent to my remote machines.  

how can I pass an $arg into a Workflow Loop?  


mqh7

Get samAccountName from email

$
0
0
i am trying to run a script to get samaccount name from a txt or csv file that has user email address in it and export results to a txt file. 

Stonecold31666


Office 365 edit user details using powershell

$
0
0

Hi,

I am trying to write a short script to add mobile numbers to multiple office365 users. Each time I run the script I get different results. Sometimes it will work, sometimes it looks to work but does nothing, and sometimes it says 'the command was run successfully but user ** was not changed'

Could someone please let me know what is wrong with my script - I am new to powershell!

Import-CSV c:\telephone.csv | Foreach{Set-user $_.AccountName -MobilePhone $._MobilePhone}

Many thanks

Collect Registry Data on Remote Machine, without invoke-command and with credentials?

$
0
0

Hi,

So I'm struggling to find a way to collect all of the registry entries in "SOFTWARE\Microsoft\Windows NT\CurrentVersion" on a remote machine, that I can pass login credentials to. I'm looking to replicate what Win32_Product does initially, but will also want to grab other info from the registry too. I've read that Win32_Product isn't a good idea to run as it can cause issues, its also slow as hell. So I'm trying to figure out an alternative.

I'm trying to convert a VBS script over into Powershell, got everything working. But this.

The Get-WmiObject seems like the way to do it, but I can't figure out how to get it to grab multiple entries like Win32_Product does.

$reg = Get-WmiObject -List -Namespace root\default -ComputerName $Computer -Credential $Cred | Where-Object {$_.Name -eq "StdRegProv"}
$HKLM = 2147483650
$reg.GetStringValue($HKLM,"SOFTWARE\Microsoft\Windows NT\CurrentVersion","ProductName").sValue

This will grab a single value, but I can't figure out how to modify it so that I can get all values.

My attempt at modifying it with the below doesn't work. :(

$reg = Get-WmiObject -List -Namespace root\default -ComputerName $Computer -Credential $Cred | Where-Object {$_.Name -eq "StdRegProv"}
$HKLM = 2147483650

$RegKey = $reg.EnumValues($HKLM,$KeyAddress)

$SubKeys = $RegKey.GetSubKeyNames()

Foreach($key in $SubKeys) {
    $thiskey = $UninstallKey+"\\"+$Key
    $ThisSubKey = $Reg.OpenSubKey($ThisKey)
    $DisplayName = $ThisSubKey.GetValue("DisplayName")
    Write-Host $ComputerName, $DisplayName
}


...

Using .Net works, kind of - But ...

1) I can't work out how to pass credentials

2) The below code will only pull the root folders of HKEY_LOCAL_MACHINE. The OpenSubKey isn't doing what I'd expect.

3) I'll need to modify it so that it actually writes results to an object/array.

$key = "SOFTWARE\Microsoft\Windows\CurrentVersion"
$type = [Microsoft.Win32.RegistryHive]::LocalMachine
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($type, $Computer)
$regKey = $regKey.OpenSubKey($key)
Write-Host "Sub Keys"
Write-Host "--------"
Foreach($sub in $regKey.GetSubKeyNames()){$sub}
Write-Host
Write-Host "Values"
Write-Host "------"
Foreach($val in $regKey.GetValueNames()){$val}

I feel like I've checked every link online about this to no avail.

If only Get-ItemProperty had a -MachineName -Credentials properties! It's so tidy, simple and fast... :(

Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | select DisplayName, Publisher, InstallDate

Just as a further note, this codes going into RunSpaces to be performed in parallel. But I can't guarantee that Invoke-Command will be enabled on the target computer. I'm also trying to target the script to run in Powershell 2.0 if possible.

Thanks for any help or links that will point me in the right direction.


Script to get the amount of windows updates on remote machine

$
0
0

Hello evereybody!

I need a script to get the amount of windows updates on sigle remote machine and on multiple machines. Can anybody help me out?

Thanks.


Bruno Prata

$Profiles = $ProfileManager.GetEnumerator()

$
0
0

Hi

Is it possible to target specific users with the above PowerShell in a specific company in AD?

cheers

Shane

mulitple varibles into a export-csv path

$
0
0

#get the current date
$CurrentDate = Get-Date
$CurrentDate = $CurrentDate.ToString('yyyyMMdd')

$Group = "test"
$out = "C:\Users\jlawson23\Desktop\scripts\Groups\Domain_$ADGroup_GROUPSOUT$CurrentDate.csv"

So when I call my command and I run:

| Export-csv -path $out

I expect a file name created:

C:\Users\jlawson23\Desktop\scripts\Groups\Domain_test_GROUPSOUT20161222.csv

Instead I get:

C:\Users\jlawson23\Desktop\scripts\Groups\Domain_20161222.csv

If I modify this command:

$out = "C:\Users\jlawson23\Desktop\scripts\Groups\Domain_'$ADGroup'_GROUPSOUT$CurrentDate.csv"

I get:

C:\Users\jlawson23\Desktop\scripts\Groups\Domain_'test'_GROUPSOUT20161222.csv

but I don't want the ' in the filename.  Anyway I can get what I want?

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>