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

Unable to fecth EmployeeID from diffrent forest

$
0
0

I'm trying to fecth employeeID from diffent forest and getting null, fine with all other attibutes and same script is working for local domain without any issue. Please let me know how to get the same.

Get-ADUser user -Server dc.local.com:3268 -properties * | Select DisplayName, employeeID



Powershell Script to Delete Users Profile if placeholder file is older than 30days

$
0
0
File server with folder structure as follows:
DATA$(Top Level Share)
 Folder1
 Folder2
 Folder3
 etc
 etc


Check each subfolder of Data$ for the existence of a text file named "mig.txt"
If "mig.txt" doesn't exist
 Then Do Nothing
If "mig.txt" exists
 Check "mig.txt" creation date
If creation date is over 30days ago
 Delete contents of subfolder

I want to run the above as a scheduled Task once a day from the file server


Powershell - Display registry key remotely.

$
0
0

Hello.

The below works locally.  How do I query the same info using WMI on a remote computer?  WinRM is disabled on remote computers so I cannot use invoke-command.  Thank.s

$Key="HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"
Get-ChildItem $key -Name

Thanks.

Try statement is missing its catch or Finally block.

$
0
0

I am a newbie when it comes to writing powershell scripts. I have a line of code that has an error in it.      

 if($MissingFile.SideIndicator -eq "<=") { $Output.process="Copy File" } try { $Output.Message="Copying missing file : $($TargetFolder+"\"+$MissingFile.Name)"} Write-Log $Output.Message Copy-Item -LiteralPath ($SourceFolder+"\"+$MissingFile.Name) -Destination ($TargetFolder+"\"+$MissingFile.Name) -WhatIf:$WhatIf $Output.Successful=$TRUE } catch { $Output.Message="Error copying missing file $($TargetFolder+"\"+$MissingFile.Name)" Write-Log $Output.Message -IsError Write-Log $_ -IsError elseif ($MissingFile.SideIndicator="=>")}
            {

Can anyone assist in explaining the catch or finally block that is missing?

Identify post powershell 5.1 pending reboot status

$
0
0

I'm trying to figure out a way to determine if a server has a pending powershell 5.1 update and is pending a reboot.

I've installed powershell 5.1 on some servers. We held off rebooting until there's a windows.

I thought the test-pendingreboot.ps1 was correctly identifying that a server was waiting on a reboot to finish installing powershell 5.1. Nope, it is not.

I need a way to identify a server is pending a reboot for powershell update to 5.1 only.

Is that possible?

Thanks in advance. 

Get-WmiObject - Sum all DriveLetter for Server total

$
0
0

We have a script that provides the break down of all of the Drives per server, however I can't seem to get a total of all drives.  I have to end up adding a subtotal in excel but think there should be a way to incorporate a foreach or something to get the total in the script:

# current version - 01/13/2015

Param (
	$computers = (Get-Content  "C:\scripts\schtasks\Computers.txt")
)


$fragmentsDetail = @()

$data = Get-WmiObject -Class Win32_volume -computer $computers -filter "drivetype=3"

$groups = $Data | Group-Object -Property __Server

ForEach ($computer in $groups)
{
	
	$drives = $computer.group
	
	$csvdetail = $drives | Select @{ Name = "Server"; Expression = { $computer.name } },
		@{ Name = "Drive"; Expression = { $_.DriveLetter } },
		@{ Name = "SizeGB"; Expression = { ($_.Capacity/1GB -as [int]) } },
		@{ Name = "UsedGB"; Expression = { "{0:N2}" -f (($_.Capacity - $_.Freespace)/1GB) } },
		@{ Name = "FreeGB"; Expression = { "{0:N2}" -f ($_.FreeSpace/1GB) } }
	$csvDetail = $csvDetail | convertto-csv -NoTypeInformation
	$fragmentsDetail += $csvDetail
	$fragmentsDetail += "`r`n"
} 

$fragmentsDetail | Out-File driveDetailReportFSA.csv

Please let me know if more information is needed.

Thanks,


Jr. Admin

Failed to update Help for the module(s) 'Microsoft.PowerShell.Operation.Validation' with UI culture(s) {en-US}

$
0
0

I am trying to update the help files for PowerShell, and I am running into the following error:

C:\WINDOWS\system32> Update-Help
Update-Help : Failed to update Help for the module(s) 'Microsoft.PowerShell.Operation.Validation' with UI culture(s) {en-US} : The value of the HelpInfoUri key in the module manifest must resolve to a container 
or root URL on a website where the help files are stored. The HelpInfoUri 'https://www.msn.com/?ocid=NEFLS000' does not resolve to a container.
At line:1 char:1+ Update-Help+ ~~~~~~~~~~~+ CategoryInfo          : InvalidOperation: (:) [Update-Help], Exception+ FullyQualifiedErrorId : InvalidHelpInfoUri,Microsoft.PowerShell.Commands.UpdateHelpComman

Possibly useful information regarding my PowerShell version:

PS C:\WINDOWS\system32> $PSVersionTable

Name                           Value                                                                                                                                                                                
----                           -----                                                                                                                                                                                
PSVersion                      5.1.14393.0                                                                                                                                                                          
PSEdition                      Desktop                                                                                                                                                                              
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}                                                                                                                                                              
BuildVersion                   10.0.14393.0                                                                                                                                                                         
CLRVersion                     4.0.30319.42000                                                                                                                                                                      
WSManStackVersion              3.0                                                                                                                                                                                  
PSRemotingProtocolVersion      2.3                                                                                                                                                                                  
SerializationVersion           1.1.0.1    

How can I fix this?

check status health hard disk (raid)

$
0
0

Hi Everyone,

Could you help me please with getting notification Health Disk status on email , what I did wrong I received empty email I did not see any info, thank you very much !!

$ServerName = "myservername"
$sender = "sender@email"
$Subject = $ServerName + " - Check Disk Health " + $TimeNow.datetime


$SmtpServer = "SMTPmyserver"

$logs = Get-PhysicalDisk | Sort Size | FT FriendlyName, Size, MediaType, SpindleSpeed, deviceid, HealthStatus, IsOffline, OperationalStatus -AutoSize
$LogOnRecords = "Health Disk Check"


    Send-MailMessage -To "my@email.com" -from $sender `
    -subject $Subject -Smtp $SmtpServer `
    -body $LogOnRecords


Reading key value pairs from Powershell

$
0
0

Hi All.

I am trying to read key valued pairs from a vault system and was wondering what is the most efficient way of doing this and also converting into a standard function. Once given a URL, I would like the function/routine to be able to read all the keys and values and then this can be converted into a string to be used within variables.

This is what I have so far.

$pass = @{
      password='xxxxxxxxxxxx'
}
$body = (ConvertTo-Json $pass)
$secret_url_login = "http://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/loginname"

$result1 = Invoke-RestMethod -secret_url $secret_url_login -Method Post -Body $body
$authct = $result1.auth.client_token

$secret_url_metadata = "http://xxxxxxxxxxxxxxxxxxx/status/project1"
$header = @{'X-Vault-Token'=$authct}
$raw_result = Invoke-RestMethod -secret_url $secret_url_metadata -Method Get -Headers $header
$result_data = $raw_result.data

From the vault this is what the Json looks like

{"host": "server123","department": "department","rack": "false","owner": "business","environment": "Development","location": "USA West"
}

From Powershell 

$result_data looks like the below.

@{host=server123; department=department; rack=false; owner=business; environment=Development; location=USA West}

Redirect (Save) Output to an Existing File

$
0
0

Hello Everyone,

Just to start with, I am a new user of Powershell so please excuse me if you find my inquiry dumb. :)

I have a command which is "cleartool space -vob \test | select -last 1 |ForEach-Object {Write-Host ($_ -split ' ')[5,7,8]}" that gives me an output of \test 400 Mb. I want this output to be saved in a file calledD:\BackupFiles\result.txt.

I tried executing the command "cleartool space -vob \test | select -last 1 |ForEach-Object {Write-Host ($_ -split ' ')[5,7,8]} | Out-File D:\BackupFiles\result.txt -Append"but this doesn't save the output to the file. Instead, it shows only the output in the screen.

I tried also "cleartool space -vob \test | select -last 1 |  ForEach {Write-Output ($_ -split ' ')[5,7,8]} | Out-File D:\BackupFiles\result.txt -Append"instead of the Write-Host and it indeed saved to the file but instead of a one-liner, it saves as 3 lines like this:

\test

400

Mb

Can you please tell me what is wrong with the command I executed and what is the right way instead?

Your help is much appreciated.

Best regards,

Maria


Find all files within a folder that has been modified in X Days

$
0
0

Hi,

Wonder if you can help me,

I am looking at finding the way to find the way to get if any file's and subfolders within a folder if they haven't been modified within X Days, then to copy the item to another location

So we have Folder A > Subfolder A > File A> 
File A has has been modified within the last 2 days then do not move Folder A

This has files and Subfolders and Files within this. If any child file or folder hasn't been amended, then its needed to copy whole parent and all child items to another location.

This is what i have come up with but it copies the files and leaves the child items that have been modified/

get-childitem -Path "FileLocation" -Recurse -file | where-object {$_.LastWriteTime -lt (get-date).AddDays(-300)} | move-item -destination "Destinationlocation" " -force | ForEach-Object{ if(Test-Path $Destination$($_.Name)){Remove-Item $_ -Force}} 


import-csv remove carriage return in column

$
0
0

Hi! I'm fairly new to powershell. I've been having a bit of trouble with import-csv and I hope you guys can help me. I have a list of csv files(mostly winevent log reports). Some of them have a column named "Message" and some don't. What I would like to do is if the csv file contains the column "Message", remove the \r\n in the values.

I tried to do it this way but it doesn't work...what am I doing wrong?

(this is inside a foreach loop, looping through csv files in my csv file list)

import-csv $SourceFile | select * -ExcludeProperty "__mv_*","_mkv_*"| Foreach-Object {
                                    foreach ($property in $_.PSObject.Properties){
                                        if($property.Name -match "Message"){
                                           $_.Message = $_.Message -replace "`r`n",' '
                                        }
                                    }
                                }| export-csv -path $TempFileUTF8 -Encoding UTF8 NoTypeInformation

this noob needs your expertise!


Powershell export to CSV

$
0
0

Hi,

I've been working on copying a script we've used at my workplace previously. This script through Powershell is supposed to find the computer's name, and operativesystem as well as systemversion and servicepack (if any), and have this exported to Excel. Or rather CSV as the format mostly used from what I can see.

My issue however is that upon opening the CSV file, for each computer the info will be squashed into the first box on each line. I'd much prefer if each bit of information automaticly was assigned to each box in the file to make it automaticly more organized. Is this possible to do?

The command I use for this result is as following:

Get-ADComputer -Filter "Name -like 'COMPUTERNAME*'" -Property * | Select-Object Name,OperatingSystem,OperatingSystemServicePack,OperatingSystemVersion | Export-CSV All-Windows.csv -NoTypeInformation -Encoding UTF8

How to increase the Powershell's memory?

$
0
0

In asp.net MVC web app, I was trying to connect the remote Exchange server through powershell , these are the codes:

 ...

runspace = RunspaceFactory.CreateRunspace(connectionInfo);

try {

runspace.Open(); // the error comes from this line

....

Connecting to remote server ProdServer.ca failed with the following error message :
<f:WSManFault xmlns:f="http://schemas.microsoft.com/wbem/wsman/1/wsmanfault" Code="3762507597"
Machine="ProdServer.CA"><f:Message><f:ProviderFault provider="PowerShellplugin"
path="%windir%\system32\pwrshplugin.dll"></f:ProviderFault></f:Message></f:WSManFault>
For more information, see the about_Remote_Troubleshooting Help topic.

After googling , it seems it caused there is no enough powershell memory, is this related to my local machine (localhost) who is running this C# codes or it is remote server computer? and how to increase the memory space?

I tried this codes :  winrm setwinrm/config/winrs `@`{MaxMemoryPerShellMB=`"512`"`} , but it is doesnot work.

Is this related to Powershell version? does different powershell has different command to increase the space?

I am using Windows 10 with Visual Studio 2017 Enterprise version.   

thanks

Pass values from an external powershell script to an inline script

$
0
0

Hi, I have a release definition that runs a powershell script in one task and I would like to pass the value of that script to an inline script in another task in the release definition.  I don't know if this can be done, and if it can I don't know how to do it.

Any advice would be appreciated!


Tim


how to avoid overwriting the output with select -ExpandProperty

$
0
0

When i try with below command the output is getting overwrriten. Please let me know how to avoid it.

The input file contains multiple colum with employeeid coloum and i'm trying to pull user based on employeeid, i'm able to see complete report on powershell but Only the problme with exporting.

$a = Import-Csv C:\gp.csv | select -ExpandProperty employeeid
foreach ($b in $a)
{Get-ADUser -filter { employeeid -eq $b } -Properties * | select DisplayName, samaccountname, employeeid |Export-Csv -Path C:\sl.csv -NoTypeInformation}

Having Problems with Control Structures loops in my menu script

$
0
0

I created a menu on Pshell to excute the different options based on the user's response. But I want to handle error handling for dates (i.e it is not in the correct format mm/dd/yyyy) and the end after a cycle through my do loop, a user chooses a option whether or not they want to continue with the program or not. When I try to prompt the user if they wish to continue at the end,if I type in nonsense like "sdgahadhd" it won't display what I show which is invalid response and go back to "Do you wish to continue(Y/N)" 

Write-host "Invalid Response"

Also when  Im going through the do while loop for a second round, it wont prompt anymore about dates and go directly to  

"Please enter 1 of the following 5 selections (First Report/Our Tasks,Second Report/Our Tasks, Combined Report/Our Tasks, Combined Report/All Tasks,Exit)"

which is an issue because I want it to continually prompt me for dates in my do while loop.

Is there a way where I can fix my script to meet those conditions as described above? Thanks!

My script

$GroupArray = @(
    'a'
    'b'
    'c'
)

do {
cls
while ($Date1 -notmatch '^\d{2}\/\d{2}\/\d{4}$') {
$Date1 = Read-Host "Please enter the first date(format is mm/dd/yyyy)"
}
cls
while ($Date2 -notmatch '^\d{2}\/\d{2}\/\d{4}$') {
$Date2 = Read-Host "Please enter the second date(format is mm/dd/yyyy)"
}
cls
[String]$Response = Read-Host "Please enter 1 of the following 5 selections (First Report/Our Tasks,Second Report/Our Tasks, Combined Report/Our Tasks, Combined Report/All Tasks,Exit)"
cls
switch($Response) {"FirstReport/Our Tasks" {Import-CSV -Path 'C:\Temp\FirstReport.csv' |  Where { ([DateTime]$_.'Date 1' -ge [DateTime]$Date1) -and ([DateTime]$_.'Date 2' -le [DateTime]$Date2) -and ($_.'Assignment Tasks' -in $GroupArray) } | Export-Excel -Path "C:\Temp\FirstReportDate.xls" -Title "First Report";pause;break}"Second Report/Our Tasks" {Import-CSV -Path 'C:\Temp\SecondReport.csv' |  Where { ([DateTime]$_.'Date 1' -ge [DateTime]$Date1) -and ([DateTime]$_.'Date 2' -le [DateTime]$Date2) -and ($_.'Assignment Tasks' -in $GroupArray) } | Export-Excel -Path "C:\Temp\SecondReportDate.xls" -Title "Second Report";pause;break}"Combined Report/Our Tasks" {Import-CSV -Path 'C:\Temp\CombinedReport.csv' |  Where { ([DateTime]$_.'Date 1' -ge [DateTime]$Date1) -and ([DateTime]$_.'Date 2' -le [DateTime]$Date2) -and ($_.'Assignment Tasks' -in $GroupArray) } | Export-Excel -Path "C:\Temp\Combinedreportdate.xls" -Title "Combined Report";pause;break}"Combined Report/All Tasks" {Import-CSV -Path 'C:\Temp\Combinedreport.csv' |  Where { ([DateTime]$_.'Date 1' -ge [DateTime]$Date1) -and ([DateTime]$_.'Date 2' -le [DateTime]$Date2) } | Export-Excel -Path "C:\Temp\CombinedreportDate.xls" -Title "Combined Report"}"Exit" {Write-host "Exiting script now";pause;exit}
default {Write-host "Invalid Selection"; pause;break}
}
cls

[String]$terminate = Read-Host "Do you wish to continue (Y/N)"

if ($terminate -eq "N") {

exit;
}
elsif ($terminate -ne "Y") -or ($terminate -ne "N") {
Write-host "Invalid Response"
}

}while($true)

Powershell Robocopy

$
0
0

All,

I am trying to robocopy some files and retain the folder structure to a specific location.

 

I have a text file that contains 1 row with the following

  • C:\Users\User1\Desktop\Folder\file.doc
  • C:\Test\test.xlsx
  • C:\Program Files\Test Folder\Test.ppt

Etc......   about 400 lines

I save those results to a variable

$results = get-content -path C:\somefolder\source.log
$Robocopy = C:\windows\system32\robocopy.exe

$Destination = Z:\Documents\Backup\

I want to iterate through that list and use robocopy to copy the files to another location and retain the folder structure.

the issue is that I would love if the destination location can somehow strip the C:\ from the results and robycopy with folder structure after the C:\ so here is an example of how I would like the final folder to look like.

  • Z:\Documents\backup\Users\User1\Desktop\Folder\file.doc
  • Z:\Documents\backup\Test\test.xlsx
  • Z:\Documents\backup\Program Files\Test Folder\Test.ppt

How to call a specific version of PowerShell from C#?

Download and Install Powershell 7

$
0
0

I used the following to install Powershell 7. The installation finished without error but using $PSVersionTable.PSVersion, the version is still 5 even after reboot. Please advise. Thanks

iex"& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI -Preview"

Viewing all 21975 articles
Browse latest View live


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