Loading...

Follow Reddit - PowerShell on Feedspot

Continue with Google
Continue with Facebook
or

Valid

i want to release dhcp lease using the wmi-objects method, i cant seem to find the right syntax for it online, can someone help me release the dhcp lease for ethernet0? i believe the method is called ReleaseDHCPLease(); but idk how to use it, please and thank you.

submitted by /u/ShahanB
[visit reddit] [comments]
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Hi, I'm very new into the world of scripting and programming in general.

I need to create a script that displays a message if certain Windows configuration is not as expected. I have done most of the script, but it fails when it's run as a scheduled task. The part that runs the message is this:

 Start-Process "warning.bat" 

As you can see it's a .bat file. If I execute the .ps1 manually it displays the warning, but not if the script runs as a scheduled task

Any idea?

submitted by /u/IntentoDeAstronauta
[visit reddit] [comments]
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

I am stuck trying to figure this one out. I am building a script to automate printer installations. I have most of the script working, but one of the issues I have in my environment is that sometimes when setting the DNS record it takes a few minutes the DNS changes to be reflected on the print server. This is even after running an ipconfig /flushdns. Usually, when I update the dns record, I have to try flushing the DNS cache a few times before the device is pingable by host name.

I thought it would be really cool to build into the script a do until, or do while loop of some sorts that firsts flushes the dns cache on the remote print server. I have tested the below successfully for flushing dns cache

Invoke-WmiMethod -class Win32_process -name Create -ArgumentList ("cmd.exe /c ipconfig /flushdns") -ComputerName $Server

Next I would want to have the remote print server ping the printer by host name. I have tested the command below successfully

(Invoke-Command -computername $Server { test-connection -ComputerName $PrinterName }

If the ping test fails. I would want to run the flush the dns cache then try another ping, and keep looping until the printer is finally online, and then I would run the rest of the script to add the printer port and printer.

Is there any way I can do this? Everything I've been reading on test-connection loops has you run the test-connection on the do section with a quiet switch and stored in a variable, and then run "until" the test connection variable equals true.

submitted by /u/DNM13
[visit reddit] [comments]
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Hi all,

I'm working on a part of a script that collects the Monitors and their respective Serial Numbers attached to a computer and export it to a CSV file. Since I won't know the number of monitors attached to every system, I am using a foreach statement to collect all the monitors.

The problem is the CSV file won't update correctly. If I run the script on a computer with one monitor, the CSV file will show "Monitor 1" and "Monitor 1 Serial Number". If I run the script on a computer with two monitors and have it output to the same CSV file, it will only show "Monitor 1" and "Monitor 1 Serial Number", however I am expecting it to add "Monitor 2" and "Monitor 2 Serial Number". Can anyone offer some suggestions? Here's my script so far:

# Get monitor info $MonitorNumber = 0 $MonitorCounter1 = -3 $MonitorCounter2 = -2 $MonitorCounter3 = -1 $Monitors = Get-WmiObject -Namespace "root\WMI" -Class "WMIMonitorID" function GetMonitorInfo { foreach ($Monitor in $Monitors) { ([System.Text.Encoding]::ASCII.GetString($Monitor.ManufacturerName)).Replace("$([char]0x0000)","") ([System.Text.Encoding]::ASCII.GetString($Monitor.UserFriendlyName)).Replace("$([char]0x0000)","") ([System.Text.Encoding]::ASCII.GetString($Monitor.SerialNumberID)).Replace("$([char]0x0000)","") } } # CSV properties $infoObject = New-Object PSObject foreach ($Monitor in $Monitors) { $MonitorNumber++ $MonitorCounter1 = $MonitorCounter1 + 3 $MonitorCounter2 = $MonitorCounter2 + 3 $MonitorCounter3 = $MonitorCounter3 + 3 $Monitor = GetMonitorInfo | Select-Object -Index $MonitorCounter1,$MonitorCounter2 $MonitorSN = GetMonitorInfo | Select-Object -Index $MonitorCounter3 $Monitor = $Monitor -join ' ' Add-Member -InputObject $infoObject -MemberType NoteProperty -Name "Monitor $MonitorNumber" -Value $Monitor -Force Add-Member -InputObject $infoObject -MemberType NoteProperty -Name "Monitor $MonitorNumber Serial Number" -Value $MonitorSN -Force } $infoObject $infoColl += $infoObject # Export info to CSV file try { $infoColl | Export-Csv -Path "$pwd\Monitors.csv" -NoTypeInformation -Append -Force Write-Host -ForegroundColor Green "Inventory was successfully updated!" exit 0 } catch { } throw "Unable to export to the CSV file. Please check the permissions on the file." 

Thank you!!!

submitted by /u/cyanghost109-
[visit reddit] [comments]
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

When I want to run Powershell code that interacts with Office 365, it seems that sometimes I am required to login twice.

  1. New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $O365Cred -AllowRedirection
  2. Connect-MSOLService

What is the difference between these two commands, and why might they require two separate logins? I would think after I have logged in to Office 365 for step #1, I would be good to run Powershell commands against Office 365.

submitted by /u/RocksArePhun
[visit reddit] [comments]
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

I have the following script:

$IDs = import-csv -path "C:\temp\New folder\UPN_List.csv" ForEach ($ID in $IDs) { get-aduser -filter {CustomAttribute3 -like "$ID"} -Properties * | Select-Object name,samaccountname | Export-Csv -Path "C:\temp\New folder\String3_Names4.csv" - append } 

It works if I individually take the get-aduser command and replace the "$IDS" with an actual ID. I get the output file with the name and samaccountname info I need.

However, when I run the script it will not work The output file remains blank.

For the life of me, I can't figure out why. I get no errors, the command looks like it completed after a few seconds but the export file remains blank.

My CSV file has "IDS" as the header and the ID's listed one to each line.

What am I doing wrong and how do you know what is wrong in the future?

*Edit: corrected script syntax.

submitted by /u/InCan2
[visit reddit] [comments]
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Hello all!

I am a powershell noob at the moment so please don't laugh to hard if I am writing this script completely wrong. What I'm trying to accomplish is a powershell script that will gracefully shutdown all running VM's and then restart my hyper-v host. So the steps I need in this script are 1) Get list of running VM's. 2) For each VM in the list, shutdown VM. 3) For each VM in list, check VM status is Off, 4) If VM is not OFF, wait x amount of time and check again. 5) Proceed with host reboot.

This is what I have so far. I'm not sure if it's correct or not but I'm currently stuck on how to proceed with the if then statement. I appreciate any help. Thanks.

$vmhost = "Hypervhost" Write-Host (Get-Date)": Shutdown Running VMs on $vmhost" $runningVM = Get-VM -ComputerName $vmhost| where.object state -eq 'running' foreach ($cn in $runningVM) {Stop-VM $cn.name -asjob} Write-Host (Get-Date)": Checking Virtual Machine Power State on $vmhost" if ($runningVM.state -eq "Off") { Restart-Computer -Force } else 
submitted by /u/Stelic83
[visit reddit] [comments]
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

I'm really struggling to redirect standard error in a reliable way. I wrote this:

$output = (& $Command @($Arguments) '2>&1') -Join "`r`n"

And it worked exactly how I wanted it to. $Command is the full path to a .bat file. $Arguments is a string array (I don't think I need the @() but I wasn't sure). The problem is that, when I used a different $Command value (when it is the full path to a .exe (psql.exe for working with postgres)) '2>&1' doesn't redirect the output.

Instead it is treated as another argument. The program complains that "psql: FATAL: database "2>&1" does not exist"

If I change my code to be:

$output = (& $Command @($Arguments) 2>&1) -Join "`r`n"

The psql.exe command runs great. BUT....the batch file no longer has it's stderr redirected!

I'm really just trying to write a function that runs a command, with N arguments that are passed in as an array of strings, and be able to return the output (standard output and standard error). Feels like it should be straight forward. Can someone help me understand what I'm doing wrong?

submitted by /u/VisaEchoed
[visit reddit] [comments]
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

I've been trying to adapt various scripts out there to get members of security groups that have nested groups in them. The problem I'm finding is scripts that do work either won't return results if a nested group is from a parent or external domain, or it won't return the properties I'm looking for.

For instance, this is great because it's simple, but it doesn't tell me if an account is disabled, or show the parent group of each account:

Get-content C:\aaa.txt | ForEach-Object{ $groupname = $_ Get-ADGroupMember $groupname -Recursive | Where-Object{ $_.objectClass -eq 'User' } | Select-Object *, @{ n = 'GroupName'; e = { $groupname } } } | Select-Object GroupName, samAccountName | Export-csv "C:\output.csv" -NoTypeInformation 

Ideally, I'm looking for something that allows me to take a txt file of groups, and output a csv listing users that are nested via groups while showing which group they belong to, and if they are disabled. I'd appreciate any help anyone can give me.

submitted by /u/qckslvr42
[visit reddit] [comments]
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Hey all,

I have a bit of experience writing in-line scripts in PS, but really want to speed things up by converting a few to operate in parallel. Every morning, I execute 9 scripts, in succession, that hit about 200 servers to query metadata (hardware config, drive sizing, service accounts, admin accounts, patch history, reboot history, etc) and store it all in a SQL Server database. Executing these 9 scripts against ~200 servers takes upwards of 45 minutes to complete. My hope would be to convert each of the 9 scripts to operate in some sort of parallel fashion rather than connecting to 1 server at a time.

Here is the code I have so far, just trying to output the SQL command to screen rather than write to the DB. This particular script is the first of the 9 and just ensures that I can execute PS remotely (so that any that are down just get skipped by the other scripts).

$dataSource = "DB_SERVERNAME" $Database = "DB_NAME" $ConnectionString = "Server=$dataSource;Database=$Database;Integrated Security=True;" $Connection = New-Object System.Data.SqlClient.SqlConnection $Connection.ConnectionString = $ConnectionString $Connection.Open() $getServersQuery = "select serverID, ServerName from server_MasterList where serverStatusID in (1);" $command = $connection.CreateCommand() $command.CommandText = $getServersQuery $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $SqlAdapter.SelectCommand = $command $command.Connection = $Connection $serversDataSet = New-Object System.Data.DataSet $SqlAdapter.Fill($serversDataSet) $Connection.Close() $serverMasterResults = $serversDataSet.Tables[0].Rows workflow checkAvailability{ param ($serverMasterResults) ForEach -parallel ($server in $serverMasterResults){ $OSinfo = "" $Accessible = "" #$InsertCommand = "" $serverID = $server.serverID $serverName = $server.ServerName try{ $OSInfo = gwmi -PSComputerName $server.serverName Win32_OperatingSystem -ErrorAction Stop $Accessible = $true } catch { $Accessible = $false } $InsertCommand += "Update dbo.server_MasterList set accessible = '$Accessible' where ServerID = $serverID; " } } if($serverMasterResults.Count -ge 1){ checkAvailability write-host $InsertCommand } 

Unfortunately, the output writes the result count and then a single line with an update statement:

Update dbo.server_MasterList set accessible = 'False' where serverID = 199

It only takes a second or so to execute. Clearly it's not iterating but only execute for the first result in the query.

Does anything stick out in how I have written the workflow?

submitted by /u/alelock
[visit reddit] [comments]

Read for later

Articles marked as Favorite are saved for later viewing.
close
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Separate tags by commas
To access this feature, please upgrade your account.
Start your free month
Free Preview