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

How to get a list of inactive users that are not presented from a specific ou

$
0
0

<p>I want to get a specific list of users, who disabled, and not presented from specific OU

I have a PSH string, but it is not working correctly

Get-ADUser -Filter * | Where-Object {$_.Disabled -eq $true} | -SearchBase "OU=Disabled,DC=TEST,DC=TEST" | Select-Object SAMAccountName,EmployeeNumber | Export-Csv -Path C:\disabled.csv -NoTypeInformation


How to capture error details within a while loop? … in PowerShell

$
0
0
I have a power shell script that checks if the connection to an Ip address is live. I have added a timer to the code so it loops and checks for 4 minutes then sleeps then starts again. I have also added this script to task schedule that runs every 5 minutes.

However my problem is the script only capture the error details if the errors occurs outside the while loop. If there is an error while the code is looping, the error variable is empty and unfortunately all the errors occur withing the loop.

This is the code I have. Apart from the above, everything works fine. Any suggestions or answers?

functionMake_Decision(){if($val -eq 0){
        $msg ="Connection to [$IPaddress] FAILED`n"Add-Content-path C:\path\results.txt -value "[$date] - { $msg }"Send_Email_Groups}}## Connection Test FunctionfunctionTest_Port_Connection(){
    $date =Get-Date-Format g
    $portNumber =0000
    $IPaddress ='000.00.00.00'
    $timeout = new-timespan -Minutes4
    $sw =[diagnostics.stopwatch]::StartNew()## Establishing TCP Connection
    $host_connection =New-ObjectSystem.Net.Sockets.TCPClient
    try {
        $host_connection.Connect($IPaddress, $portNumber)}
    catch {
        $erro ="[$date] - $_"#Add-Content -path C:\path\errors.txt -value "[$date] - { $erro }"
        $erro |Out-File C:\path\errors.txt -Append}while($sw.elapsed -lt $timeout){#while loop startsif(($host_connection.Connected)-and (Test-Connection-IPAddress $IPaddress -Count1-ErrorActionSilentlyContinue)){
            $val =1}else{
            $val =0break}
        start-sleep -Seconds1}# end of while loopMake_Decision}Test_Port_Connection

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

2 line PowerShell script works on one device, but not the other

$
0
0

Hello,

The below 2 line code at the end of this message does a filter on only *.msi files (there will only be one in the directory, so not worried about multiple *.msi files) to the specified path to only return the name of the *.msi file to a message box and no other information. 

One one device it works fine and on the other it gets this error message below.  I did a search on the Internet, but I did not find anything specific to this error message:

Get-ChildItem : Cannot call method. The provider does not support the use of filters.
At line:1 char:20
+ ... aNameOnly = Get-ChildItem -filter *.msi -Path \\server_name\share_name
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotImplemented: (:) [Get-ChildItem], PSNotSupportedException
+ FullyQualifiedErrorId : NotSupported,Microsoft.PowerShell.Commands.GetChildItemCommand

 Here is the 2 line code that gets the file name and then sends that output to a message box:

$GetFileNameOnly = Get-ChildItem -filter *.msi -Path \\server_name\share_name –Name
[System.Windows.MessageBox]::Show($GetFileNameOnly)


Formatting powershell results

$
0
0

Hello,<o:p></o:p>

I'm using JumpCloud powershell module for exporting command results.

I'm trying to format powershell result but unable to export all columns. 
>get-jccommandresult -byid 5c7fe06eba87c603cb1ddf4a | select name, command, system, output | format-table -wrap -autosize                     <o:p></o:p>

This works perfectly fine, but  i'm only selecting specific jccommandresult and i want to export all jccommandresults without filtering by id. But when I export, the “output” column is blank. I’m not sure if it is because of the output column format in the result displayed.

Below are the commands that I tried but couldn’t get “output” column result in exported file.

(I want the result to be in table format so that I can filter it by name and system so I didn’t use format-list. Also, I read somewhere that format-table wont work with export-csv but I tried that too.)

get-jccommandresult | Select name,command,system,output,_id | export-csv -path C:\Users\abc\Documents\JCcmdres.csv -append

get-jccommandresult | select name, command, system,output,_id | format-table -wrap -autosize |out-file -filepath C:\Users\abc\Documents\JCcmdres.csv -width 4096 -append

get-jccommandresult | select name, command, system,output,_id | Out-GridView

get-jccommandresult | Select name,output,system |convertto-csv -notypeinformation | out-file -filepath C:\Users\abc\Documents\JCcmdres.csv -width 4096 -append

How to get a file shared folders including hidden folders using powershell script

$
0
0
I want to find script to get the all file share folders including hidden folders.

PowerShell Script fails to run when scheduled

$
0
0

Hello Ladies & Gentlemen,

I have a powershell script, which runs absolutely fine when I run with ISE.

When I schedule the script. It runs and fails. I am not able to figure out why the script is failing when run as schedule job.

I see the following error in the transcript logs. Although it says username and password is incorrect, it doesn't make much sense as the it's the same user under which I run script when using ISE.

PS>TerminatingError(New-Object): "Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 8000401a The server process could not be started because the configured identity is incorrect. Check the username and password. (Exception from HRESULT: 0x8000401A)."
New-Object : Retrieving the COM class factory for component with CLSID
{00024500-0000-0000-C000-000000000046} failed due to the following error:
8000401a The server process could not be started because the configured
identity is incorrect. Check the username and password. (Exception from
HRESULT: 0x8000401A).
At G:\AutomationScript\AutomateReferesh.ps1:39 char:13+ $excelObj = New-Object -Com Excel.Application+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : ResourceUnavailable: (:) [New-Object], COMExcept
   ion+ FullyQualifiedErrorId : NoCOMClassIdentified,Microsoft.PowerShell.Comman
   ds.NewObjectCommand

Here is the legendary script

# To Debug, uncomment Start-Transcript line

Start-Transcript -Path "G:\AutomationScript\transcript0.txt" -NoClobber -Force -Append

# Load .Net Assembly for Excel
Add-Type -AssemblyName Microsoft.Office.Interop.Excel

# ********** Update the $CurrentFilePath & $CurrentFileName variable with Actuals  **********#

# Current File Path of Excel
$CurrentFilePath = "G:\AutomationScript\"

# HardCode FileName
$CurrentFileName = "FileName.xls"


# Load Previous Day File
$previousDay = (Get-Date).AddDays(-1).ToString("ddMMyyyy")

# Dynamically build CurrentFileName
$CurrentFNFP = $CurrentFilePath + $previousDay + "_" + $CurrentFileName

# Test Path
if(!(Test-Path($CurrentFNFP)))
    {
        $CurrentFNFP = $CurrentFilePath + $CurrentFileName
    }

#Build Time Stamp for New FileName
$TimeStamp = (get-date -Format ddMMyyyy).ToString()

#Build New File Name
# $NewFileName = $NewFilePath.Path + "\" + $TimeStamp + "_" + $CurrentFileName

$NewFileName = $CurrentFilePath + $TimeStamp + "_" + $CurrentFileName

#Create the Excel Object
$excelObj = New-Object -Com Excel.Application

#Wait for 5 seconds then update the spreadsheet
Start-Sleep -s 5

#Make Excel visible. Set to $false if you want this done in the background
$excelObj.Visible = $false
$excelObj.DisplayAlerts = $false

#Open the workbook
$workBook = $excelObj.Workbooks.Open($CurrentFNFP)

#Wait for 5 seconds then update the spreadsheet
Start-Sleep -s 5

#Focus on the top row of the "Data" worksheet
#Note: This is only for visibility, it does not affect the data refresh
$workSheet = $workBook.Sheets.Item("ToDoList")
$workSheet.Select()

#Refresh all data in this workbook
$workBook.RefreshAll()

Start-Sleep -s 5

#Save any changes done by the refresh
$workBook.SaveAs($NewFileName)

Start-Sleep -s 5

$workBook.Close()

#Uncomment this line if you want Excel to close on its own
$excelObj.Quit()
$excelObj = $null

#write-host "Finished updating the spreadsheet" -foregroundcolor "green"
Start-Sleep -s 5

##### Email the results #####

# Date Format for Email
$Fdate = (Get-Date -Format "dd MMMM yyyy")



# Reading the username and password securely for SMTP Relay from XML
[xml]$Relay_config = Get-Content $CurrentFilePath\Relay_config.xml

$Relay_SecurePassword = ConvertTo-SecureString $Relay_config.Configuration.Password
$Relay_UserName = $Relay_config.Configuration.UserName
$Relay_UserCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Relay_UserName,$Relay_SecurePassword

# Update the $recepients with a single distribution email address or multiple email address as shown below

$recepients = "automate@domain.com"

#Send Email with attachment to DistributionList. Update the To, From, SMTPServer and, optionally Subject, Body 
Send-MailMessage -To $recepients  -From "user@domain.com" -Subject "Updated Excel for $Fdate" -Body "Kindly find updated Excel (ADP) for $Fdate" `
                 -Attachments "$NewFileName" -SmtpServer "smtp.office365.com" -Port 587 -Credential $Relay_UserCredential -UseSsl


Regards, Navdeep


Install OS with DSC

$
0
0

Hi Guys,

I really hope that someone did this or that someone knows how to do it. I am in process of automating server deployment and I am using DSC to install roles and to configure servers. No problem there. But before doing it I need to install windows server OS first and that is soemthing I want to avoid. I know that we can use diffrerencing disks for this but I want to fresh install OS with DSC for every VM not to use parent disk. Is it possible to use DSC to install new VM and to install windwos server on it?


Adding Script automatically on TaskSchduler

$
0
0

Hi 

I m new to scripting. I working on script to to add domain member to local Admin account and remove it automatically after a certain period of time.  After referring posts online i could able to add or remove accounts from a machine. I don't have programming skill and i stuck up with the step 3

Step are like

1. Get Input 

$DomainName = "xxxxx" #Read-Host -Prompt "Domain name:"
$ComputerName = Read-Host -Prompt "Computer name:"
$UserName = Read-Host -Prompt "User name:"

while(1){
Try{
$d = [datetime](read-host 'Enter any valid valid date/time')
break
    }
Catch{
Write-Host 'Not a valid date' -fore red
    }
}

$AdminGroup = [ADSI]"WinNT://$ComputerName/Administrators,group"
$User = [ADSI]"WinNT://$DomainName/$UserName,user"

2. Add the user account to local admin group

$AdminGroup.add($User.Path)

3. Create a PS file on the local machine and update it with command to remove the account

Connect-PSSession -ComputerName $ComputerName
New-Item -ItemType "directory" -Path "\\$ComputerName\c$\temp"
New-Item -ItemType "file" -Path "\\$ComputerName\c$\temp\test.ps1"
Add-Content \\$ComputerName\c$\temp\test.ps1 "$AdminGroup.remove($User.Path)"

4. Add the created Script file on the Task Scheduler to run it automatically

$Trigger= New-ScheduledTaskTrigger -At $d.ToString('yyyy-MM-dd HH:mm:ss') 
$PSUser= "NT AUTHORITY\SYSTEM" # Specify the account to run the script
$Action= New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "C:\Temp\test.ps1" 
Register-ScheduledTask -TaskName "Local Account removal" -Trigger $Trigger -User $PSUser -Action $Action -RunLevel Highest –Force 

Exit-PSSession

The output at the step 3 was not as expect . the file it getting updated as 

" System.DirectoryServices.DirectoryEntry.remove(System.DirectoryServices.DirectoryEntry.Path) "

Instead of Local admin group and the user account.

Could anyone please suggest me a solution to automated it with proper output. Or a different way to derive it ?

I m not sure how the step 4 will work

Problem running Python scripts on PowerShell

$
0
0

I get this error when I try to run scripts in PowerShell. These scripts run fine in the command window. 




JohnB

DNS Response Rate Limiting

$
0
0

Hello everyone, i have been attacked multiple times by a DDos and was wondering how to get into my DNSserverrrl through powershell. I really have no understanding on how to access it and would like to learn. When i try to run the command it gives me this error. I am running Powershell(Administrator) 5.1 on Windows 10.

PS C:\WINDOWS\system32> Get-Dnsserverrrl
Get-Dnsserverrrl : The term 'Get-Dnsserverrrl' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
At line:1 char:1+ Get-Dnsserverrrl+ ~~~~~~~~~~~~~~~~+ CategoryInfo          : ObjectNotFound: (Get-Dnsserverrrl:String) [], CommandNotFoundException+ FullyQualifiedErrorId : CommandNotFoundException

Help me, Micro-Soft Kenobi... you're my only hope.



Sending email using Outlook 2016 with SendUsingAccount thru Poweshell not working

$
0
0

Im trying to send emails thru Outlook 2016 using Powershell with the following code:

$Outlook = New-Object -ComObject Outlook.Application
    foreach ($account in $Outlook.Application.Session.Accounts)
    {
        if ($account.UserName -eq "accountusername")
        {
        $thisaccount=$account
        }
    }
    $Mail = $Outlook.CreateItem(0)
    $Mail.SendUsingAccount=$thisaccount
    $Mail.To = "destination@emaildomain.com"
    $Mail.Subject = "a subject"
    $Mail.HTMLBody = "i am message<br /><br />"
    $Mail.Send()

It still sends it thru the default account. Both accounts are Exchange added accounts. In the client, manually, I can send email from both accounts so it is not a permissions issue.

Why isnt it working?

convert .eml to .msg

$
0
0

I have 500000 .eml files that needs to be converted to .msg file and save in local folder.

I want to know if we have any powershell command to do so?

Or any other efficient method to achieve this??(C#)

PS: Dont want to use third party converters.

Trying to run an EXE and a ROM and unlock my GPU but Power shell says uhmmm nope...

$
0
0

I just dont know how to get power shells command not found message gone 

CMD  line: c\USER\Desktop\Flash>"".exe "".rom unlock

*scratches heads*

Check if OST in Outlook is synchronized by script

$
0
0

Hi Team,

I has made a script that delete the ost file at logoff, if it grows up to 50GB.

I have a lot of Outlooks 2010 clients with 2 Exchange accounts ... there are some circunstances in wich the users move mails / folders between the both accounts, close Outlook, force to Windows logoff and the emails get lost .. there aren't in any account.

I have looked on Office Object Model but couldn't find a way to check if all OSTs are synchronized with the Exchange...

So, anyone knows how to check if an OST file is full synchronized with the Exchange? Powershell script prefered.

Checking this GUI's item on the script could work:


Many thanks guys!


Execution policy modification audit trail

$
0
0

What's the best way to track execution policy changes on a server?  One of the engineers on my team inadvertently changed the execution policy on a production server to Restricted which caused a whole bunch of tasks to fail.  I spent hours trying to figure out who did it but none of the event logs on the server are showing who did it and when. 


List Version of MS Office

$
0
0

Hello

I want to edit a powershell script that gives me the different version of MS Office install the PCs of a very specific OU.
Thank you for your help

Mahdi, 


Mehdi

Posh5 Create Class with constructor code

$
0
0

I don't want to sound like I know what I'm doing here...

Is it possible to add code to an object that will execute when an object is created?

In the simple class below, is the "If" statement valid?  In other words, how can I instruct the "constructor"?  How can I manipulate elements of the object as it is built, and potentially execute conditional code?

Class FirstClass

{ [string]$Name

 [string]$Property1
 [string]$Property2

 If( $Name -EQ '' ){ $Name = "$Property1-$Property2" }
}

using rsrestsession with Write-RsRestCatalogItem

$
0
0
Dear all,

i try to deploy a report with Powershell. I  installed RS module.
It works fine if i use -Credential 'domain\xxx' and enter my password when prompting.

But now, I would like to automate process, and so, use WebSession argument instead of Crendential.


here is what I'm doing:

$Username = 'domain\xxx'

$Password = 'xxx'

$pass = ConvertTo-SecureString -AsPlainText $Password -Force $SecureString = $pass
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$SecureString
$session = New-RsRestSession -ReportPortalUri https://myserver/reports -Credential $MySecureCreds


The session is well created (receive error if bad password).

Now I run:


Write-RsRestCatalogItem -ReportPortalUri 'https://myserver/reports' -Path "D:\xxx\xxx.rdl" -RsFolder "/My Reports" -WebSession $session

I got:

System.Exception: Failed to create catalog item: The remote server returned an error: (401)


What I'm wrong ?


Thanks in advance.
regards,
Xavier

convert to array got err as its fixes size

$
0
0
$t=@()
$r= new-object -type PSObject
class
{
[string]$a
[string[]]$b

}

$c =get-adgroupmember -recrisive $team| select SamAccountName  

$c.b = $c.SamAccountName
$c.a="dummy"
$t += $c

$r | add-member -name 'c' -type noteproperty -value $t
$r| convertto-json | out-file -filepath .\xyz.json -NOClobber -force

this script give 
{
d: [
"a" : "\"sda"\", "\sdd"\"
]
}
the json is not properly printed also shall I declare $t in class, the slashes are there

Viewing all 21975 articles
Browse latest View live


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