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

Get the ReleaseID on a remote system

$
0
0

Hello

I am trying to find a way to get the windows releaseid from a remote computer, but am having a hard time finding a way to do it.

I'm trying to use:

(Get-ItemProperty -Path ‘HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion’).ReleaseId

But have not found a way to tell it to look on a remote system.  I have also tried using the invoke-command and using the -computername, but again, it fails.

$hostname ="City-Spare71"
$OScompID = Get-ADComputer -Filter {Name -eq $Hostname} | Select Name
Invoke-Command -Computername $OSCompID {(Get-ItemProperty -Path ‘HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion’).ReleaseId}

Here's the error:

Invoke-Command : One or more computer names are not valid. If you are trying to pass a URI, use the -ConnectionUri parameter, or pass URI objects instead of strings.
At line:1 char:1+ Invoke-Command -Computername $OSCompID {(Get-ItemProperty -Path ‘HKLM ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (System.String[]:String[]) [Invoke-Command], ArgumentException+ FullyQualifiedErrorId : PSSessionInvalidComputerName,Microsoft.PowerShell.Commands.InvokeCommandCommand

$OSCompID does return the right value.

Any suggestions?  I'm looking for a 1 liner

Thank You

Terry


setup schedule task

$
0
0

I am trying to create a schedule task using the -RandomDelay switch.   

$action = New-ScheduledTaskAction -Execute 'shutdown.exe' `
  '/r /t 0 /c "Task Schedule Reboot" /f '

$trigger =  New-ScheduledTaskTrigger  -Once -At 5pm  -RandomDelay 8
$principal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet -MultipleInstances Parallel

Register-ScheduledTask -TaskName "Reboot Task" -TaskPath "Acme" -Action $action -Trigger $trigger -Settings $settings -Principal $principal

The code above works but it sets the -RandomDelay to 8 DAYS.  I've tried many different text formats but so far nothing has worked.  How do I set it to 8HOURS?  


mqh7


Edit Administrators local group of a remote PC

$
0
0

I'm trying to make a script to edit the Administrators local group of an arbitrary remote PC. The user will usually have rights to the remote PC via their current credentials but not always - sometimes the user must supply credentials. I'm able to make the script only prompt for credentials if it fails to connect to the remote PC with the credentials of the running PowerShell session - this feature is a must-have. Unfortunately, this creates an issue when the user's current credentials are for a different forest than the remote PC. I can recreate this behavior outside of the script:

  • If the correct credentials are provided before attempting to use the remote computer then there is no problem. (This proves there is no firewall issue, rights issue, etc.)
  • If using the remote PC is attempted with the current credentials and it fails, then the remote PC can't be used immediately after the correct credentials are provided. It will fail over and over for about 2 minutes before it works. Closing PowerShell and opening it again avoids the 2-minute wait.

To recreate, first do this knowing that your current ID does not have rights to somepc.somedomain.com on a different forest:

$sPCtest = 'somepc.somedomain.com' ; # change this string
Remove-Variable oPCtest, AdminGroupTest 2> $Null
$oPCtest = New-Object System.DirectoryServices.DirectoryEntry("WinNT://$sPCtest")
$AdminGroupTest = $oPCtest.psbase.children.find("Administrators")

I get the error, 'Exception calling "Find" with "1" argument(s): "The network path was not found."' Now do this before about 2 minutes passes:

$credTest = Get-Credential
Remove-Variable oPCtest, AdminGroupTest 2> $Null
$oPCtest = New-Object System.DirectoryServices.DirectoryEntry("WinNT://$sPCtest", $credTest.UserName, $credTest.GetNetworkCredential().password
)
$AdminGroupTest = $oPCtest.psbase.children.find("Administrators")

I get the error, 'Exception calling "Find" with "1" argument(s): "Unspecified error"'. Then skip the 1st variable assignment and repeat the remaining commands. It will eventually work after about 2 minutes.

I didn't bother with sample code using the $AdminGroupTest object. If PowerShell defines it without an error then it always works afterwards in my experience, e.g. Add and Remove methods.

Note for testing: If you successfully define the the $AdminGroupTest object, then you will have a connection to IPC$ on the remote PC. You should run 'net use "\\$sPCtest" /d' before attempting to start a test over from the beginning.

So, how can I avoid waiting 2 minutes?

Powershell delete multiple files from multiple computers not working exactly as I require

$
0
0

I have this script that I have compiled from different scripts to get exactly what I need.

The filelist looks something like this:

D$\Test1\*

D$\Test2\*

Now I want to delete the file in all of the subfolders of Test1 and Test2, but not actually delete any subfolders. At this stage the script does not recognise that there are files in the subfolders, so I get "No files to delete" in the log and nothing is deleted. The file count is also not working as expected, either reporting 1 or 0, which I guess is counting the folder and not the files. Any help to improve this would be highly appreciated.

function Write-Log($string)
{
    $outStr = "" + $Timestamp +" "+$string

    Write-Output $outStr

   }

$Timestamp = Get-Date -Format "yyyy-MM-ddTHH-mm-ss"
$filelist = Get-Content C:\support\scripts\filelist.txt
$computerlist = Get-Content C:\support\scripts\computerlist.txt
$Log = "c:\support\scripts\logs\Delete_Old_Files_$(Get-Date -Format 'yyyyMMddhhmmss').log"

Start-Transcript -path $Log -append -Force -NoClobber
Write-Log "------------ Start of Log  ------------"

foreach ($file in $filelist) {
    foreach ($computer in $computerlist){
        Write-Log "Analysing $computer"

        $newfilepath = Join-Path "\\$computer\" "$file" 
        if (test-path $newfilepath) {
            Write-Log "$newfilepath folder exists"
            try
            {
                Remove-Item $newfilepath -Recurse -force -ErrorAction Stop | Where-Object { -not ($_.psiscontainer) }
            }
            catch
            {       
                $ErrorMessage = $_.Exception.Message
                $FailedItem = $_.Exception.ItemName
                Send-MailMessage -From aaa@@aaa.com -To bbb@bbb.com -Subject "Old Files Delete Failed!" -SmtpServer bla.com -Body "The error message is: '$ErrorMessage'"
                Break
            }
            Write-Log "$newfilepath files deleted"
        } else {
            Write-Log "Path $newfilepath no files to delete"
        }
        # output statistics
  Write-Output "**********************"
  #Write-Output "Number of old files deleted: $($_.Count)"
  Write-Log "------------- End of Log -------------"
    }
}


 Stop-Transcript


Get-EventLog - Faster Method?

$
0
0

I wrote a script to gather 1139 event logs from all the 2008/2012 DCs, but it takes forever to run.

I'm guessing there is a different method I could use to filter this, that would result in a faster return of results, but the other methods I have tried all failed / resulted in the same speed.

Then command I'm using is:

Get-EventLog -ComputerName $Computer -LogName 'Directory Service' -After (Get-Date).AddHours(-3) | Where-Object {$_.EventID -eq 1139} -ErrorAction SilentlyContinue | Select-Object -Property TimeGenerated,MachineName,UserName,@{N='IP:Port';E={$_.Properties.Value[3]}}

Any thoughts on faster method?

Thanks!


There's no place like 127.0.0.1

how to get the time diffrence from givn times in file

$
0
0

I have file with below data, I want to get the highest time difference from this using PowerShell.

STARTTIME:2018-12-01 04:13:15
ENDTIME:2018-12-01 04:17:15
-----------------------
----------------------
STARTTIME:2018-12-01 04:11:15
ENDTIME:2018-12-01 04:13:15
------------------------
-----------------------
STARTTIME:2018-12-01 04:10:15
ENDTIME:2018-12-01 04:10:40

Split function -split a word with dot into two strings

$
0
0

Hello Team,

I have facing some issue with strings and split strings on dot.

I need to import a column from excel sheet which looks like this 601,601,607, 601.02,602.01.601.20, 701,702, 701.01" and so on.

There are two possible values either the input number has a dot or it does not have a dot.

My algorithm is as below,

1. Read excel cell, compare with regex

2 If regular expression match split the string on dot else color the cell background to orange,

goto step 4

3. check if the first part of the string is part of the hash table which has approved list if match\contains the value color corresponding cell to green , if no color column blue

4. if more cells goto step 1 else goto step 5

5. exit function, close excel.


My code snippet is as follows

if($worksheet.cells.Item($i, $RoomNumberColumn).value2 -match "^[0-9]{3}([a-c]{1})?([.]{0,1})?([0]{1})?([1-20{1})?$")
                  {
                  $option = [System.StringSplitOptions]::RemoveEmptyEntries

                  [String]$RoomNumber= $worksheet.cells.Item($i, $RoomNumberColumn).value2
                  [string]$RoomNumberParts=$RoomNumber.split(".",2,$option)
                  Write-Host "Value of Number--> $RoomNumberParts and" $RoomNumberParts[0]
                  if($hashRoomNumber.ContainsKey($RoomNumberParts[0]))

                  {$worksheet.cells.Item($i, $RoomNumberColumn).Interior.ColorIndex = 35;}
                  Else {$worksheet.cells.Item($i, $RoomNumberColumn).Interior.ColorIndex = 37;}
                  }
 
        
        Else
        {
        $worksheet.cells.Item($i, $RoomNumberColumn).Interior.ColorIndex = 45;
        }
 


Question: Why is my string not breaking up into the two parts eg. 607 and 02  and instead when I try to access $RoomNumberParts[0] I am getting a 6 and not value 607. Kindly assist me to split the string into two parts only  601 and 02

thanks,

RJ



install-windowsfeature error

$
0
0

hello,

i am getting the following error at a dc:

anyone who can tell me what i am doing wrong?


PowerShell - Searching Excel and replacing text

$
0
0

Hi all,

I am trying to figure out how to loop this script so that it replaces all the text that I am searching for in my Excel file.  I am able to get it to run but it only replaces the text in the first column and then ends. Any help is appreciated and thanks in advance.

-Gaz

$File="D:\test.xlsx"

# Setup Excel, open $File and set the the first worksheet
$Excel=New-Object-ComObjectExcel.Application
$Excel.visible=$true
$Workbook=$Excel.workbooks.open($file)
$Worksheets=$Workbooks.worksheets
$Worksheet=$Workbook.Worksheets.Item(1)

$SearchString="TEMP# This is the value that I will be searching for

$Range=$Worksheet.Range("A1").EntireColumn
$Search=$Range.find($SearchString)

$Search.value()="ABSENT"# This is the value that i want to replace the text with.

Getting multiple lines between two strings

$
0
0

Hi Experts,

I am stuck in a code, my requirement is to get the lines between two strings, please suggest a regex pattern

Input:

Device Name: test
Status: Completed
Results:
[PUSH_TERMLET] Action completed successfully...
Pushing configuration file 'PUSH_TERMLET' for IDX 60504 with mechanism SSH
****** Enable Mode Results ******
sh run | sec ip access-list standard customer_internal
ip access-list standard customer_internal
 permit 204.79.49.116
 permit 159.12.130.0 0.0.0.31
 permit 10.108.30.0 0.0.0.255
 permit 10.108.141.0 0.0.0.127
 permit 10.108.172.0 0.0.0.255
 permit 10.108.160.0 0.0.0.31
zapesxr01#

Output:

 permit 204.79.49.116
 permit 159.12.130.0 0.0.0.31
 permit 10.108.30.0 0.0.0.255
 permit 10.108.141.0 0.0.0.127
 permit 10.108.172.0 0.0.0.255
 permit 10.108.160.0 0.0.0.31

Here is the code that i am  trying 

$content = Get-Content -Path "TestACL.txt"

$device_list = $content | Select-String -Pattern "device name" -AllMatches

 foreach($temp in $device_list){

 $temp.sp

 $pattern = "(?<=$temp|permit)(.*)"

$content | Select-String -Pattern $pattern

 }

Awaiting a solution!

Placing this code in a scriptblock

$
0
0

Hi All.

I am trying to place the code below in a sriptblock, not sure about the format.

$root_drive = "D"
	New-Partition  -DiskNumber 1 -DriveLetter $root_drive -Size 20GB
	Format-Volume -DriveLetter $root_drive  -FileSystem NTFS -NewFileSystemLabel “D_” -Confirm:$false -Force

In previous examples, I have seen

$scriptblock = $ExecutionContext.InvokeCommand.NewScriptBlock("Remove-DnsServerResourceRecord -ZoneName $ZoneName -ComputerName $DCName -Name $HostName -RecordData $IPv4Address -RRType A -Force")


extract data from all group policies

$
0
0

I have many group policies in my domain and I want make a report in excel which shows the following:

Group policy name       Restricted Groups   Members        Memberof

GPO1                          Group1                                       Builtin\administrators

Currently I have extracted all the GPO's in html file and used select-string cmdlet to find the pattern "Restricted Groups".

This gives me all the policies having the restricted groups settings defined in them. However I want to generate a report as shown

above from all the groups policies which have the restricted groups settings defined. Is there any automated way to achieve this?

Script to Get DNS configuration of Remote Windows servers

$
0
0

Hi,

I am writing a Script in PowerShell, to obtain the DNS Configurations of remote Windows servers.

I am reading the server name from a text file.

I want to use the NetIPConfiguration command in the script and then store the output in a file.

What is the WmiObject class for NetIPConfiguration ? or any script for the same would be great.

 

Unable to catch SMTP errors while sending mail using Send-MailMessage

$
0
0

I have got a list of report in which few users are not in the organization, in such cases when the script tries to send email to those invalid addresses i should be able to catch errors, which is not happening. Can someone help to fix this?

Moving certs between stores using powershell v3

$
0
0

Hello,

I'm trying to write a script that will test to see if a particular certificate is there and if so move it to the disallowed store.  I've written this script but I can't figure out why it's not working.  No errors are returned but it just doesn't do anything.  Any help would be appreciated.

# requires -version 3
$servername = Hostname
$file = get-childitem Cert:\LocalMachine\AuthRoot | where {$_.thumbprint -eq '4EB6D578499B1CCF5F581EAD56BE3D9B6744A5E5'}
$trusted_path = "cert:\localmachine\authroot"
$Untrusted_path = "cert:\localmachine\disallowed"


if (Test-Path -path $trusted_path)
    {
    Move-item "cert:\localmachine\authroot\$file" -destination $untrusted_path -Force
    }
Else
    {
     write-host "The certificate is not in the AuthRoot Folder on server $servername"
    }

Thanks...


Jeff Stewart


Unable to get the used space and free space using the new-psdrive command. I am using the below code. The code is running without error but not getting the used space and free space of the disk

$
0
0
Function CleanUp-PSDrive {
    Get-PSDrive -PSProvider FileSystem | Where { $_.Name -in (69..90 | ForEach-Object { [char]$_ })} | Remove-PSDrive
}

$Csv = Import-Csv "Path"

$Csv.Name | ForEach-Object -Begin { $Letter = 69 } {

 New-PSDrive -Root  $_ -Name([char]$Letter) -PSProvider FileSystem 




 
 

    if ($Letter -lt 90) 
    { 
      $Letter++ 
    } 
    else 
    { 
        CleanUp-PSDrive
        $Letter = 69
    }
} -End { CleanUp-PSDrive } | select used,free | export-csv "Path" -NoTypeInformation

Trimming a string with = (Equals) sign

$
0
0

Hopefully a quick one for someone. 

$string = "CN=Network"

I'm trying to loose the "CN="

PS C:\Windows\system32> $string
CN=Network

PS C:\Windows\system32> $string.TrimStart("CN=")
etwork # note the missing "N"

How do i keep my N? 

Thanks

Looking for a script to retrieve all mail contacts and its mail group memberships

$
0
0

Need to inventory all contacts (external recipients) and find out if each is in any of DLs.  I can get a list of mail contacts (Get-MailContact).  But Exchange 2016 mail contact object has no attribute for group memberships.  Looks like I have to query AD for object type of Contact.  Is that correct?  The query has to be based on display name since mail contact has no AD account (SAM ID).  Can anyone recommend a script?

Thanks.

Unable to run SETSPN command remotely using INVOKE-COMMAND

$
0
0

Hi All,
I came across interesting issue where I have a requirement to run SETSPN command remotely using INVOKE-COMMAND Or PSSESSION. 
When I run the below command directly on my desktop, it runs fine without any issue. 

setspn -S HOST/MYCNAME -C REDMOND\MYServerName

But when I use INVOKE-COMMAND option, I'm getting error. Has anyone solved this in the past? Can you suggest me how to solve this puzzle? 

INVOKE-COMMAND -computername MyServerName {(setspn -S HOST/MyCNAME -C REDMOND\MyServerName)}
Ldap Error(0x1 -- Operations Error): ldap_get_next_page_s    + CategoryInfo          : NotSpecified:
(Ldap Error(0x1 ...get_next_page_s:String) [],
Checking domain DC=redmond,DC=corp,DC=microsoft,DC=com
Error occurred when searching for existing SPN: 0x00000001
Error
Ldap Error(0x1 -- Operations Error): ldap_get_next_page_s
    + CategoryInfo          : NotSpecified: (Ldap Error(0x1 ...get_next_page_s:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
    + PSComputerName        : MyServerName
Checking domain DC=redmond,DC=corp,DC=microsoft,DC=com
Error occurred when searching for existing SPN: 0x00000001



Enable MFA in O365 through AD group membership?

$
0
0
Total Newbie here. Trying to create a security group in AD where a powershell script will enable MFA in O365 based on this group membership? Can anyone point me in the right direction?  Thanks in advance.
Viewing all 21975 articles
Browse latest View live