Microsoft
Software
Hardware
Network
Question : ForEach and ForEach-Object not the same?
I was hoping someone could help me with this. I have a script in which I used many aliasesI was going through and removing all aliases to make it easier for people who aren't familar with PS to read.
When I change line 14 from foreach to foreach-object, it breaks the scripts and I get
Unexpected token 'in' in expression or statement.
At C:\Users\albinoanteater\HS
N\Scripts\
RestartSer
vice2.ps1:
14 char:27
+ foreach-Object($Srv in <<<< $TextFile)
Any ideas?
Here is the full script.
$TestFileLocation=$args[0]
$ServiceName=$args[1]
if ($ServiceName -eq "")
{
Write-Host "Usage:Powershell RestartService2.ps1 ServerListFilename ServiceName";
exit;
}
else
{
$YMD = Get-Date -uformat %Y%m%d%H%M
$TextFile = Get-Content "$TestFileLocation"
$Result = @()
foreach($Srv in $TextFile)
{
"Info_: Stopping $ServiceName on $Srv at $YMD"
$ResultStop = (Get-WmiObject -computer $Srv Win32_Service -Filter "Name='$ServiceName'").Sto
pService()
if ($ResultStop.ReturnValue -eq "0")
{
"Info_: The $ServiceName has been stopped. Now restarting."
$ResultStart = (Get-WmiObject -computer $Srv Win32_Service -Filter "Name='$ServiceName'").Sta
rtService(
) | Select-Object ReturnValue
"Info_: The Return Value is $resultstart"
}
else
{
"Error: The $ServiceName on $Srv has failed to stop. Skipping this service."
}
}
}
Thanks in advance.
AlbinoAnteater.
Answer : ForEach and ForEach-Object not the same?
Yes the usage is different. You need to do
$TextFile | ForEach-Object
{
$Srv = $_;
http://blogs.msdn.com/jman
ning/archi
ve/2007/03
/22/powers
hell-
gotch
a-foreach-
keyword-vs
-foreach-o
bject-cmdl
et.aspx
Random Solutions
How to setup NAC Agent to be running at system startup and as a service, not as an application?
Search not returning results
relaying denied IP name lookup failed
Are there any viruses for compress files zip, rar, 7zip, is there a way to prevent them?
Sybase max table and column name length
DNS issues on Mac Server
Deploying and using Active Sync in a secured (non-admin) environment
how to recover exchange mailboxes from priv1.edb file
does xp media center have a msconfig utility
how to protect my live tv streaming